前言
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)