Java並發工具類之線程間資料交換工具Exchanger

來源:互聯網
上載者:User

標籤:資料   人工   exe   new   特殊情況   錯誤   檢查   線程   tor   

  Exchanger是一個用於線程間協做的工具類,主要用於線程間的資料交換。它提供了一個同步點,在這個同步點,兩個線程可以彼此交換資料。兩個線程通過exchange方法交換資料,如果一個線程執行exchange方法,它就會等待另一個線程執行exchange方法,當兩個線程都到達了同步點,這兩個線程就可以交換資料。將本線程產生的資料傳送給對方。

  Exchanger可用於工作的互相校對,比如我們要把線下產生的交易資料通過人工錄入的方式添加到系統中,為了避免錯誤,我們採用AB兩人同時錄入的方式,當錄入完成後,系統分別載入AB兩人錄入的資料,檢查是否出錯。

  類比執行個體如下:

  

public class ExchangerTest {    //定義交換器    private static final Exchanger<String> exchanger = new Exchanger<String>();    private static ExecutorService threadPool = Executors.newFixedThreadPool(2);    public static void main(String[] args){        threadPool.execute(new Runnable() {            @Override            public void run() {                String strA = "a record data";                try {                    exchanger.exchange(strA);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        });        threadPool.execute(new Runnable() {            @Override            public void run() {                try {                    String strB = "b record data";                    String strA= exchanger.exchange(strB);                    System.out.println(strA.equals(strB));                    exchanger.exchange(strB);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        });    }}

  如果兩個線程有一個沒有執行exchange()方法,則會一直等待,如果擔心有特殊情況發生,避免一直等待,可以使用exchange(V x,longtimeout,TimeUnit unit)設定最大等待時間長度。

Java並發工具類之線程間資料交換工具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.