类 Exchanger 的功能可以使2个线程之间传输数据,比生产者/消费者模式方便。
Exchanger类的结构很简单,重点就是exchange()方法。
exchange()方法是阻塞执行的,可以设置超时时间,调用不同的api即可。
exchange 的 英文意思就是交换,而对于线程而言也是这样的,就是两个线程交换信息。如果共有3个线程,且3个线程同时调用了exchange,那么就会有一个线程没有交换信息的对象,就会继续阻塞。
下面是一个例子:
共有两个类 ExchangerThread、ExchangerTest:
package com.cd.concurrent.exchanger;import java.util.concurrent.Exchanger;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;public class ExchangerThread extends Thread { private Exchangerexchanger; private String name; public ExchangerThread(String name, Exchanger exchanger) { super(); this.name = name; this.exchanger = exchanger; } @Override public void run() { try { // System.out.println("线程[" + name + "]拿到消息:" + exchanger.exchange(name + "-msg")); // 不设置超时时间,线程会一直阻塞等待 System.out.println("线程[" + name + "]拿到消息:" + exchanger.exchange(name + "-msg", 5, TimeUnit.SECONDS)); // 设置5秒的超时时间 System.out.println("线程[" + name + "]over"); } catch (InterruptedException e) { e.printStackTrace(); } catch (TimeoutException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
package com.cd.concurrent.exchanger;import java.util.concurrent.Exchanger;public class ExchangerTest { public static void main(String[] args) { Exchangerexchanger = new Exchanger (); ExchangerThread t1 = new ExchangerThread("t1", exchanger); ExchangerThread t2 = new ExchangerThread("t2", exchanger); ExchangerThread t3 = new ExchangerThread("t3", exchanger); t1.start(); t2.start(); t3.start(); }}
运行结果: