import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
publicclass ExchangerTest {
publicstaticvoid main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool(); //缓存线程池(动态)
final Exchanger exchanger = new Exchanger();
service.execute(new Runnable(){
public void run() {
try{
String data1 = "zxx";
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(){
publicvoid run() {
try{
String data1 = "lhm";
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){
}
}
});
}
}
多线程并发库工具类Exchanger
最新推荐文章于 2024-05-30 20:17:45 发布