码迷,mamicode.com
首页 > 编程语言 > 详细

线程的工具类(Exchange)

时间:2017-02-10 01:57:33      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:工具   current   ati   and   ide   nts   ring   爱情   cache   

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="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 = 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)

标签:工具   current   ati   and   ide   nts   ring   爱情   cache   

原文地址:http://www.cnblogs.com/wanglaicai/p/6384698.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!