Exchanger

Posted hts-technology

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Exchanger相关的知识,希望对你有一定的参考价值。

Exchanger 用于两个线程之间交换数据,举例;

package com.hts;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExchangerTest {
    class Product implements Runnable{
        Exchanger<Integer> exchanger ;
        Product(Exchanger<Integer> exchanger ){
            this.exchanger = exchanger;
        }
        @Override
        public void run() {
            int data;
            for(int i = 1;i<11;i++){
                data = i;
                System.out.println("Product"+i+"交换前:" + data);
                try {
                    data = exchanger.exchange(data);
                    System.out.println("Product"+i+"交换后:" + data);
                    System.out.println();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class Consumer implements Runnable{
        Exchanger<Integer> exchanger ;
        Consumer(Exchanger<Integer> exchanger ){
            this.exchanger = exchanger;
        }
        @Override
        public void run() {
            int data = 0;
            for(int i = 1;i<11;i++){
                data = 0;
                System.out.println("Consumer"+i+"交换前:" + data);
                try {
                    data = exchanger.exchange(data);
                    System.out.println("Consumer"+i+"交换后:" + data);
                    System.out.println();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Exchanger<Integer> exchanger = new Exchanger<>();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(new ExchangerTest().new Product(exchanger));
        executorService.submit(new ExchangerTest().new Consumer(exchanger));
    }
}

执行结果:
技术分享图片

大概意思就是一个线程交换的数字是从1-10,而另一个线程则每次交换的数据都是0,可以看出这个exchanger.exchange(data);方法是一个阻塞方法,当一个线程等待交换时,一定会u等到另一个线程也执行exchanger.exchange(data)同时进行交换,交换后才会继续往下执行。


以上是关于Exchanger的主要内容,如果未能解决你的问题,请参考以下文章

java 多线程 29 :多线程组件之 Exchanger

学习了解 Exchanger - 实现生产者消费者模型

Exchanger兄弟线程间数据信息交换

一行Java代码实现游戏中交换装备

ccse(CountDownLatch,CycliBarrier,Semaplore,Exchanger)

Java并发多线程编程——并发工具类Exchanger