Java多線程編程之使用Exchanger數(shù)據(jù)交換實例
更新時間:2015年05月19日 10:07:35 投稿:junjie
這篇文章主要介紹了Java多線程編程之使用Exchanger數(shù)據(jù)交換實例,本文直接給出實例代碼,需要的朋友可以參考下
用于實現(xiàn)兩個人之間的數(shù)據(jù)交換,每個人在完成一定的事務(wù)后想與對方交換數(shù)據(jù),第一個先拿出數(shù)據(jù)的人將一直等待第二個人拿著數(shù)據(jù)到來時,才能彼此交換數(shù)據(jù)。
復(fù)制代碼 代碼如下:
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() + "正在把數(shù)據(jù)'" + data1 +"'換出去");
Thread.sleep((long)(Math.random()*10000));
String data2 = (String)exchanger.exchange(data1);
System.out.println("線程" + Thread.currentThread().getName() + "換回的數(shù)據(jù)為'" + data2+"'");
}catch(Exception e){
}
}
});
service.execute(new Runnable(){
public void run() {
try {
String data1 = "李四";
System.out.println("線程" + Thread.currentThread().getName() + "正在把數(shù)據(jù)'" + data1 +"'換出去");
Thread.sleep((long)(Math.random()*10000));
String data2 = (String)exchanger.exchange(data1);
System.out.println("線程" + Thread.currentThread().getName() + "換回的數(shù)據(jù)為'" + data2 + "'");
}catch(Exception e){
}
}
});
}
}
返回結(jié)果:
復(fù)制代碼 代碼如下:
線程pool-1-thread-1正在把數(shù)據(jù)'張三'換出去
線程pool-1-thread-2正在把數(shù)據(jù)'李四'換出去
線程pool-1-thread-1換回的數(shù)據(jù)為'李四'
線程pool-1-thread-2換回的數(shù)據(jù)為'張三'
相關(guān)文章
Java8如何利用Lambda快速生成map、多層嵌套map
這篇文章主要介紹了Java8如何利用Lambda快速生成map、多層嵌套map問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09