java 多線程 29 :多執行緒元件之 Exchanger

來源:互聯網
上載者:User

標籤:class   啟動   import   over   mem   1.5   system   0ms   blog   

Exchanger

Exchanger,從名字上理解就是交換。Exchanger用於在兩個線程之間進行資料交換,注意也只能在兩個線程之間進行資料交換。線程會阻塞在Exchanger的exchange方法上,直到另外一個線程也到了同一個Exchanger的exchange方法時,二者進行資料交換,然後兩個線程繼續執行自身相關的代碼。

Exchanger只有一個exchange方法,用於交換資料。看一下例子:

public static class ExchangerThread extends Thread{    private String str;    private Exchanger<String> exchanger;    private int sleepSecond;        public ExchangerThread(String str, Exchanger<String> exchanger, int sleepSecond)    {        this.str = str;        this.exchanger = exchanger;        this.sleepSecond = sleepSecond;    }            public void run()    {        try        {            System.out.println(this.getName() + "啟動, 原資料為" + str + ", 時間為" + System.currentTimeMillis());            Thread.sleep(sleepSecond * 1000);            str = exchanger.exchange(str);            System.out.println(this.getName() + "交換了資料, 交換後的資料為" + str + ", 時間為" + System.currentTimeMillis());        }         catch (InterruptedException e)        {            e.printStackTrace();        }    }}    public static void main(String[] args){    Exchanger<String> exchanger = new Exchanger<String>();    ExchangerThread et0 = new ExchangerThread("111", exchanger, 3);    ExchangerThread et1 = new ExchangerThread("222", exchanger, 2);    et0.start();    et1.start();}

看一下運行結果:

Thread-0啟動, 原資料為111, 時間為1444560972303Thread-1啟動, 原資料為222, 時間為1444560972303Thread-0交換了資料, 交換後的資料為222, 時間為1444560975303Thread-1交換了資料, 交換後的資料為111, 時間為1444560975303

看到兩個線程交換了資料,由於一個線程睡2秒、一個線程睡3秒,既然要交換資料,肯定是睡2秒的要等待睡3秒的,所以看到時間差是3000ms即3s。


ps:這裡感覺是,一個線程需要另一個線程跟他同步的時候  會用到 ,也可用作管道相互連知,先mark

java 多線程 29 :多執行緒元件之 Exchanger

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.