首页 > 代码库 > 线程的工具类(Exchange)

线程的工具类(Exchange)

public class Exchanger<V>extends Object

可以在对中对元素进行配对和交换的线程的同步点。每个线程将条目上的某个方法呈现给 exchange 方法,与伙伴线程进行匹配,并且在返回时接收其伙伴的对象。Exchanger 可能被视为 SynchronousQueue 的双向形式。Exchanger 可能在应用程序(比如遗传算法和管道设计)中很有用。 

实例:

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* 线程间的交换数据
*
* @author wangyi
* @version 1.0 <br />
* <a href="http://www.mamicode.com/www.baidu.com">百度一下</a>
*/
public class ExchagerTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
Exchanger<String> exchange = new Exchanger<String>();
service.execute(new MyThread<String>("爱情", exchange, "爱情"));
service.execute(new MyThread<String>("关晓彤", exchange, "关晓彤"));
service.shutdown();

}

static class MyThread<T> extends Thread {
private T data;
private Exchanger<T> exchange;

public MyThread(T data, Exchanger<T> exchange, String name) {
this.data = http://www.mamicode.com/data;
this.exchange = exchange;
setName(name);
}

@Override
public void run() {
System.out.println(getName() + "正准备把" + data + "交换出去");
try {
Thread.sleep((int) (Math.random() * 10000));
T datas = exchange.exchange(data);
System.out.println(getName() + "换回的为:" + datas);
} catch (Exception e) {
e.printStackTrace();
}

}
}

}

线程的工具类(Exchange)