轉自:https://www.cnblogs.com/java-zzl/p/9741288.html
一、通過SynchronousQueue方式實現線程間數據傳遞:
線程A與線程B共同持有一個SynchronousQueue的引用,線程B調用take方法,阻塞以等待; 線程A運行后計算出結果,將結果put到queue中;
public class SynchronousQueueTest { public static void main(String[] args) throws InterruptedException { SynchronousQueue<Integer> queue = new SynchronousQueue<Integer>(); //線程A putThread Thread putThread = new Thread(new Runnable() { @Override public void run() { System.out.println("put thread start"); try { Thread.sleep(3000); System.out.println("put thread put對象"); queue.put(1); } catch (InterruptedException e) { } System.out.println("put thread end"); } }); //線程B takeThread Thread takeThread = new Thread(new Runnable() { @Override public void run() { System.out.println("take thread start"); try { System.out.println("take thread 等待put對象"); System.out.println("take from putThread: " + queue.take()); } catch (InterruptedException e) { } System.out.println("take thread end"); } }); putThread.start(); takeThread.start(); } }
二、線程Exchanger工具類實現線程間的數據交換:
當一個線程到達exchange調用點時,如果它的伙伴線程此前已經調用了此方法,那么它的伙伴會被調度喚醒並與之進行對象交換,然后各自返回。如果它的伙伴還沒到達交換點,那么當前線程將會被掛起,直至伙伴線程到達——完成交換正常返回;或者當前線程被中斷——拋出中斷異常;又或者是等候超時——拋出超時異常。
public class ExchangerTest { public static void main(String[] args) { ExecutorService service = Executors.newCachedThreadPool(); final Exchanger exchanger = new Exchanger(); service.execute(new Runnable(){ public void run() { try { String data1 = "thread-1-data"; System.out.println("線程" + Thread.currentThread().getName() +"正在把數據" + data1 +"換出去"); Thread.sleep((long)(Math.random()*10000)); String data2 = (String)exchanger.exchange(data1); System.out.println("線程" + Thread.currentThread().getName() + "換回的數據為" + data2); }catch(Exception e){ } } }); service.execute(new Runnable(){ public void run() { try { String data1 = "thread-2-data"; System.out.println("線程" + Thread.currentThread().getName() + "正在把數據" + data1 +"換出去"); Thread.sleep((long)(Math.random()*10000)); String data2 = (String)exchanger.exchange(data1); System.out.println("線程" + Thread.currentThread().getName() + "換回的數據為" + data2); }catch(Exception e){ } } }); } }