Exchanger(交换者),它是用于线程间的协作工具类,主要用于线程间数据的交换。它提供了一个同步点,在这个同步点,两个线程可以交换彼此的数据。
代码如下:
public class ExchangerTest { private static final Exchanger<String> exchanger = new Exchanger<>(); private static ExecutorService threadPool = Executors.newFixedThreadPool(2); public static void main(String[] args) { threadPool.execute(new Runnable() { @Override public void run() { String a = "aaaaaaaaaa"; try { String b = exchanger.exchange(a); System.out.println("---" + b); } catch (InterruptedException e) { e.printStackTrace(); } } }); threadPool.execute(new Runnable() { @Override public void run() { try { String b = "bbbbbbbb"; String a = exchanger.exchange("bababa"); System.out.println("a is " + a + " , b is " + b); } catch (InterruptedException e) { e.printStackTrace(); } } }); threadPool.shutdown(); } }
输出如下:
a is aaaaaaaaaa , b is bbbbbbbb ---bababa
注意点
1、Exchanger只能作用于两个线程之间,如果作用于第三个线程,则第三个线程一直处于等待中;
2、exchange中还有一个重载函数,接收一个等待时长,用于避免一直等待。
参考: https://blog.csdn.net/qq_27828675/article/details/114068266
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!