Java Concurrent Exchanger

前言

Exchanger是JUC里提供的供兩個(gè)線程之間交換數(shù)據(jù)或者交互的一個(gè)并發(fā)工具,API也非常簡(jiǎn)單就兩個(gè)重載的exchange泛型方法。

使用的場(chǎng)景

通常用于將寫讀任務(wù)與任務(wù)邏輯處理任務(wù)分開,一個(gè)專門處理、一個(gè)專門操作。當(dāng)一個(gè)線程帶著數(shù)據(jù)調(diào)用exchange方法后,除非中斷到達(dá)時(shí)間等,否則會(huì)一直等在另一個(gè)線程,并接受其數(shù)據(jù)。
看一下demo:

import java.util.concurrent.Exchanger;
public class ExchangerDemo {
    static Exchanger exchanger = new Exchanger();
    static void startReadThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String temp="23333";
                System.out.println("ThreadA temp:"+temp);
                for(int i=0;i<10;i++){
                    System.out.println("線程A 已執(zhí)行"+i+"秒");
                    if (i==4){
                        try {
                            temp= (String) exchanger.exchange(temp);
                            System.out.println("發(fā)生數(shù)據(jù)交換");
                            System.out.println("ThreadA temp:"+temp);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
    static void startOperateThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String temp="11111111";
                System.out.println("ThreadB temp:"+temp);
                for(int i=0;i<10;i++){
                    System.out.println("線程B 已執(zhí)行"+i+"秒");
                    if (i==9){
                        try {
                            temp= (String) exchanger.exchange(temp);
                            System.out.println("發(fā)生數(shù)據(jù)交換");
                            System.out.println("ThreadB temp:"+temp);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
    public static void main(String []args) {
        startReadThread();
        startOperateThread();
    }
}

核心的實(shí)現(xiàn)函數(shù)就這兩個(gè),有興趣可以看看。
arenaExchange(Object item, boolean timed, long ns)
slotExchange(Object item, boolean timed, long ns)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容