引自:https://blog.csdn.net/Dason_yu/article/details/79764467
一、定义
每个线程将条目上的某个方法呈现给 exchange 方法,与伙伴线程进行匹配,并且在返回时接收其伙伴的对象。Exchanger 可能被视为 SynchronousQueue 的双向形式。Exchanger 可能在应用程序(比如遗传算法和管道设计)中很有用。
内存一致性效果:对于通过 Exchanger 成功交换对象的每对线程,每个线程中在 exchange() 之前的操作 happen-before 从另一线程中相应的 exchange() 返回的后续操作。(内存一致性效果被称为happen-before),简单的例子:当一个线程进行写入操作,另一个线程进行读取操作,保证一个线程写入的结果对另一个线程的读取是可视的。
二、用法
package com.thread; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExchangerTest { public static void main(String[] args) { ExecutorService service = Executors.newCachedThreadPool(); final Exchanger<String> exchanger = new Exchanger<>(); service.execute(new Runnable() { public void run() { try { String data1 = "恭喜发财!"; System.out.println("线程" + Thread.currentThread().getName() + "正在把数据:" + data1 + "换出去"); Thread.sleep((long) (Math.random() * 10000)); String data2 = exchanger.exchange(data1); System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为:" + data2); } catch (Exception e) { } } }); service.execute(new Runnable() { public void run() { try { String data1 = "乖,给你一个红包!"; System.out.println("线程" + Thread.currentThread().getName() + "正在把数据:" + data1 + "换出去"); Thread.sleep((long) (Math.random() * 10000)); String data2 = exchanger.exchange(data1); System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为:" + data2); } catch (Exception e) { } } }); service.shutdown(); } }