Java并發(fā)編程之Exchanger方法詳解
Exchanger是一個(gè)用于線程間數(shù)據(jù)交換的工具類,它提供一個(gè)公共點(diǎn),在這個(gè)公共點(diǎn),兩個(gè)線程可以交換彼此的數(shù)據(jù)。
當(dāng)一個(gè)線程調(diào)用exchange方法后將進(jìn)入等待狀態(tài),直到另外一個(gè)線程調(diào)用exchange方法,雙方完成數(shù)據(jù)交換后繼續(xù)執(zhí)行。
Exchanger的使用方法介紹exchange(V x):阻塞當(dāng)前線程,直到另外一個(gè)線程調(diào)用exchange方法或者當(dāng)前線程被中斷。
x : 需要交換的對(duì)象。exchange(V x, long timeout, TimeUnit unit):阻塞當(dāng)前線程,直到另外一個(gè)線程調(diào)用exchange方法或者當(dāng)前線程被中斷或者等待超時(shí)。
x: 需要交換的對(duì)象。 timeout:超時(shí)時(shí)間。 unit:超時(shí)時(shí)間單位。exchange方法正常情況返回交換到的對(duì)象,當(dāng)當(dāng)前線程被中斷或者等待超時(shí)時(shí),exchange方法返回null。
示例1:A同學(xué)和B同學(xué)交換各自收藏的大片
public class Demo { public static void main(String[] args) {Exchanger<String> stringExchanger = new Exchanger<>();Thread studentA = new Thread(() -> { try {String dataA = 'A同學(xué)收藏多年的大片';String dataB = stringExchanger.exchange(dataA);System.out.println('A同學(xué)得到了' + dataB); } catch (InterruptedException e) {e.printStackTrace(); }});Thread studentB = new Thread(() -> { try {String dataB = 'B同學(xué)收藏多年的大片';String dataA = stringExchanger.exchange(dataB);System.out.println('B同學(xué)得到了' + dataA); } catch (InterruptedException e) {e.printStackTrace(); }});studentA.start();studentB.start(); }}/* * 輸出結(jié)果: * B同學(xué)得到了A同學(xué)收藏多年的大片 * A同學(xué)得到了B同學(xué)收藏多年的大片 */
示例2:A同學(xué)被放鴿子,交易失敗
public class Demo { public static void main(String[] args) {Exchanger<String> stringExchanger = new Exchanger<>();Thread studentA = new Thread(() -> { String dataB = null; try {String dataA = 'A同學(xué)收藏多年的大片';//最多等待5秒dataB = stringExchanger.exchange(dataA, 5, TimeUnit.SECONDS); } catch (InterruptedException e) {e.printStackTrace(); } catch (TimeoutException ex){System.out.println('等待超時(shí)-TimeoutException'); } System.out.println('A同學(xué)得到了' + dataB);});studentA.start(); }}/* * 輸出結(jié)果: * 等待超時(shí)-TimeoutException * A同學(xué)得到了null */
到此這篇關(guān)于Java并發(fā)編程之Exchanger方法詳解的文章就介紹到這了,更多相關(guān)Java并發(fā)編程Exchanger內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案2. 利用CSS3新特性創(chuàng)建透明邊框三角3. 解析原生JS getComputedStyle4. 通過(guò)CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫(huà)特效5. CSS3中Transition屬性詳解以及示例分享6. XML入門(mén)的常見(jiàn)問(wèn)題(一)7. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案8. XML入門(mén)的常見(jiàn)問(wèn)題(二)9. 阿里前端開(kāi)發(fā)中的規(guī)范要求10. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)
