Exchanger是一個用於線程間數據交換的協做工具類,它提供一個同步點,兩個線程能夠交換彼此的數據,注意這裏只能是兩個線程。java
兩個線程經過exchange() 方法來交換數據,當第一個線程執行到exchange()時,會產生阻塞,直到另外一個線程也執行exchange(),以後兩個線程均可以獲得對方的執行結果。示例代碼以下:ide
public class ExchangerTest { private static final Exchanger<String> exgr = new Exchanger<String>(); private static ExecutorService threadPool = Executors.newFixedThreadPool(2); public static void main(String[] args) { threadPool.execute(new Runnable(){ @Override public void run() { try { String A = "this is a A"; String B = exgr.exchange(A); System.out.println("a 線程裏 a:"+A+" b:"+B); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); threadPool.execute(new Runnable(){ @Override public void run() { try { String B = "this is a B"; String A = exgr.exchange(B); System.out.println("B 線程裏 a:"+A+" b:"+B); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); threadPool.shutdown(); } }
執行結果:工具
B 線程裏 a:this is a A b:this is a B
a 線程裏 a:this is a A b:this is a Bthis
若是兩個線程有一個一直沒有執行exchange()方法,則會一直等待,若是要避免一直等待,能夠使用exchange(V x,long timeout,TimeUnit unit)設置最大等待時長。線程