可以在对中对元素进行配对和交换的线程的同步点。每个线程将条目上的某个方法呈现给 exchange
方法,与伙伴线程进行匹配,并且在返回时接收其伙伴的对象。Exchanger 可能被视为 SynchronousQueue
的双向形式。Exchanger 可能在应用程序(比如遗传算法和管道设计)中很有用。
import java.util.Random;
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<String> exchanger = new Exchanger<String>();
service.execute(new Runnable() {
@Override
public void run() {
try {
String data1 = "duwenlei";
System.out.println("线程"+Thread.currentThread().getName()+"要换的数据为"+data1);
System.out.println("线程"+Thread.currentThread().getName()+"等待对方");
Thread.sleep(new Random().nextInt(10000));
String data2 = exchanger.exchange(data1); //开始互换数据
System.out.println("线程"+Thread.currentThread().getName()+"互换后的数据为"+data2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
service.execute(new Runnable() {
@Override
public void run() {
try {
String data1 = "shenjing";
System.out.println("线程"+Thread.currentThread().getName()+"要换的数据为"+data1 );
System.out.println("线程"+Thread.currentThread().getName()+"等待对方");
Thread.sleep(new Random().nextInt(10000));
String data2 = exchanger.exchange(data1);
System.out.println("线程"+Thread.currentThread().getName()+"互换后的数据为"+data2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
service.shutdown();
}
}