正文
一、简介
Exchanger用于两个线程之间进行数据交换,每个线程调用exchage方法到达各自的同步点,当且仅当两个线程都达到同步点的时候,才可以交换信息,否则先到达同步点的线程必须等待。
二、使用案例
public static void main(String[] args) { Exchanger<String> exchanger = new Exchanger<>(); Thread thread1 = new Thread(new Runnable() { @Override public void run() { String method1 = "method1"; log.info("线程1到达同步点..."); try { String strFromThread2 = exchanger.exchange(method1); log.info("线程1获取的交换数据是{}", strFromThread2); } catch (InterruptedException e) { e.printStackTrace(); } log.info("线程1运行结束"); } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { String method2 = "method2"; try { log.info("线程2开始执行..."); // 让线程1先达到同步点 TimeUnit.SECONDS.sleep(3); log.info("线程2达到同步点..."); String strFromThread1 = exchanger.exchange(method2); log.info("线程2获取的交换数据是{}", strFromThread1); } catch (InterruptedException e) { e.printStackTrace(); } log.info("线程2运行结束"); } }); thread1.start(); thread2.start(); }
运行结果如下:
03:02:43.733 [Thread-0] INFO com.example.concurrent.ExchangerTest - 线程1到达同步点... 03:02:43.733 [Thread-1] INFO com.example.concurrent.ExchangerTest - 线程2开始执行... 03:02:46.740 [Thread-1] INFO com.example.concurrent.ExchangerTest - 线程2达到同步点... 03:02:46.740 [Thread-1] INFO com.example.concurrent.ExchangerTest - 线程2获取的交换数据是method1 03:02:46.740 [Thread-0] INFO com.example.concurrent.ExchangerTest - 线程1获取的交换数据是method2 03:02:46.749 [Thread-1] INFO com.example.concurrent.ExchangerTest - 线程2运行结束 03:02:46.749 [Thread-0] INFO com.example.concurrent.ExchangerTest - 线程1运行结束
需要注意的是,Exchanger仅可用作两个线程之间的信息交换,当超过2个线程调用同一个Exchanger时,得到的结果是不可预料的。