Exchanger能夠實現兩個線程交換數據的功能。java
demo:
線程
public static void main(String[] args) { final Exchanger<String> exchanger = new Exchanger<String>(); new Thread(new Runnable() { public void run() { String name = "Jack"; try { System.out.println(Thread.currentThread().getName() + " start.... name = " + name); name = exchanger.exchange(name); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " end.... name = " + name); } }).start(); new Thread(new Runnable() { String name = null; public void run() { try { System.out.println(Thread.currentThread().getName() + " start.... name = " + name); Thread.sleep(10000); name = exchanger.exchange(name); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " end.... name = " + name); } }).start(); }
執行結果:code
Thread-0 start.... name = Jack Thread-1 start.... name = null Thread-1 end.... name = Jack Thread-0 end.... name = null
當Thread-0執行exchanger.exchange(name)的時候進入到阻塞狀態。get
等待Thread-1也執行到exchanger.exchange(name)以後再繼續執行,兩個線程的name也相互交換告終果。io