Exchanger
java.util.concurrent.Exchanger<V> 概述:用于线程间的数据转换
API:
构造方法:
public Exchanger()
成员方法:
V exchange(V x):传递参数,参数就是你要传递的数据,返回值就是其他线程传递给你的数据
演示:
线程1:把【数据1】传递给线程2
线程2:把【数据2】传递给线程1
public class MyThread1 extends Thread{
Exchanger<String> ex;
public MyThread1(Exchanger<String> ex) {
this.ex = ex;
}
@Override
public void run() {
System.out.println("线程1:准备把数据传递给线程2");
String msg = null;
try {
msg = ex.exchange("X点X分,有【数据1】准备放鞭炮");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1:接收到线程2 的数据是:"+msg);
}
}
public class MyThread2 extends Thread{
Exchanger<String> ex;
public MyThread2(Exchanger<String> ex) {
this.ex = ex;
}
@Override
public void run() {
System.out.println("线程2:准备把数据传递给线程1");
String msg = null;
try {
msg = ex.exchange("X点X分,有【数据2】准备放鞭炮");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2:接收到线程1 的数据是:"+msg);
}
}
public class Tests {
public static void main(String[] args) {
Exchanger<String> ex = new Exchanger<>();
new MyThread1(ex).start();
new MyThread2(ex).start();
}
}