java線程中Exchanger使用,java線程exchanger

來源:互聯網
上載者:User

java線程中Exchanger使用,java線程exchanger

有時我們需要對元素進行配對和交換線程的同步點,使用exchange方法 返回其夥伴的對象,這時我們就需要使用線程類中的Exchanger類了,

我通過一個執行個體 來簡單說明一下他的使用方法及其作用:

import java.util.concurrent.Exchanger;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class TestExchanger {/** * @param args */public static void main(String[] args) {         ExecutorService executor = Executors.newCachedThreadPool();         final Exchanger<String> exchanger = new Exchanger<String>();         executor.execute(new Runnable() {String data1 = "abc"; @Overridepublic void run() {try {System.out.println(Thread.currentThread().getName() +"正在把資料 "+ data1+ " 交換出去" );Thread.sleep((long) (Math.random()*1000));String data2 = (String) exchanger.exchange(data1);System.out.println(Thread.currentThread().getName() + "交換資料 到  "+ data2);} catch (InterruptedException e) {e.printStackTrace();}}});                  executor.execute(new Runnable() {         String data1 = "def";@Overridepublic void run() {try {System.out.println(Thread.currentThread().getName() +"正在把資料 "+ data1+ " 交換出去" );Thread.sleep((long) (Math.random()*1000));String data2 = (String) exchanger.exchange(data1);System.out.println(Thread.currentThread().getName() + "交換資料 到  "+ data2);} catch (InterruptedException e) {e.printStackTrace();}}});}}

執行完畢之後;你會探索資料完成交換

pool-1-thread-1正在把資料 abc 交換出去
pool-1-thread-2正在把資料 def 交換出去
pool-1-thread-2交換資料 到  abc
pool-1-thread-1交換資料 到  def




,java中同步器的使用方法、

同步器Semaphore(一)
同步器CyclicBarrier(二)
同步器CountDownLatch(三)
同步器Exchanger(四)

想瞭解詳細:zheng12tian.iteye.com/category/149927
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.