Java多線程編程之應用Exchanger數據交流實例。本站提示廣大學習愛好者:(Java多線程編程之應用Exchanger數據交流實例)文章只能為提供參考,不一定能成為您想要的結果。以下是Java多線程編程之應用Exchanger數據交流實例正文
用於完成兩小我之間的數據交流,每一個人在完成必定的事務後想與對方交流數據,第一個先拿出數據的人將一向期待第二小我拿著數據到來時,能力彼此交流數據。
package com.ljq.test.thread;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExchangerTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final Exchanger exchanger = new Exchanger();
service.execute(new Runnable(){
public void run() {
try {
String data1 = "張三";
System.out.println("線程" + Thread.currentThread().getName() + "正在把數據'" + data1 +"'換出去");
Thread.sleep((long)(Math.random()*10000));
String data2 = (String)exchanger.exchange(data1);
System.out.println("線程" + Thread.currentThread().getName() + "換回的數據為'" + data2+"'");
}catch(Exception e){
}
}
});
service.execute(new Runnable(){
public void run() {
try {
String data1 = "李四";
System.out.println("線程" + Thread.currentThread().getName() + "正在把數據'" + data1 +"'換出去");
Thread.sleep((long)(Math.random()*10000));
String data2 = (String)exchanger.exchange(data1);
System.out.println("線程" + Thread.currentThread().getName() + "換回的數據為'" + data2 + "'");
}catch(Exception e){
}
}
});
}
}
前往成果:
線程pool-1-thread-1正在把數據'張三'換出去
線程pool-1-thread-2正在把數據'李四'換出去
線程pool-1-thread-1換回的數據為'李四'
線程pool-1-thread-2換回的數據為'張三'