Exchanger能夠在兩個線程之間交換數據,只能是2個線程,他不支持更多的線程之間互換數據。java
當線程A調用Exchange對象的exchange()方法後,他會陷入阻塞狀態,直到線程B也調用了exchange()方法,而後以線程安全的方式交換數據,以後線程A和B繼續運行。安全
今天決定花幾分鐘時間寫個小例子看下效果。如下實例演示了使用Exchange交換String數據,實際Exchange還能夠交換對對象,好比交換List,HashMap,自定義的Model等。線程
源碼以下:code
package demo19; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 使用Exchanger模擬買北京老冰棍的場景 * @author mengfeiyang * */ public class ExchangeTest { public static void main(String[] args) { ExecutorService service = Executors.newCachedThreadPool(); Exchanger<String> changer = new Exchanger<String>(); service.submit(new Runnable(){ public void run(){ try{ String data1 = "北京老冰棍"; System.out.println("線程 "+Thread.currentThread().getName()+" 正在把 "+data1+" 拿出來"); String data2 = changer.exchange(data1); System.out.println("線程 "+Thread.currentThread().getName()+"用 "+data1+" 換來了"+data2); }catch(Exception e){ e.printStackTrace(); }finally{ service.shutdown(); System.out.println(Thread.currentThread().getName()+"交易完畢,撤!"); } } }); service.submit(new Runnable(){ public void run(){ try{ String data1 = "100元"; System.out.println("線程 "+Thread.currentThread().getName()+" 正在把錢 "+data1+" 拿出來"); String data2 = changer.exchange(data1); System.out.println("線程 "+Thread.currentThread().getName()+"用 "+data1+"換來了"+data2); }catch(Exception e){ e.printStackTrace(); }finally{ service.shutdown(); System.out.println(Thread.currentThread().getName()+"交易完畢,撤!"); } } }); } }
執行結果:對象