??? 用于实现两个线程之间的数据交换,每个人在完成一定的事务后想与对方交换数据,第一个先拿出数据的人要一直等待第二个人拿着数据到来时,才能彼此交换数据
???
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() {
????????????
public
void
run() {
????????????????
try
{
?
????????????????????
String data1 =
"MacBook Pro"
;
????????????????????
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() {
????????????
public
void
run() {
????????????????
try
{
?
????????????????????
String data1 =
"8000RMB"
;
????????????????????
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.shutdown();
????
}
}
上面讲到这些看上去意义不大,其实新技术就是这个样子,你没有遇到新技术善于解决的需求,所以没有看到它的价值,不过说不定下个月,老板的需求就让你抓耳挠腮了,那个时候说不定就是这些新技术大显身手的时候
?
?
?
转自:http://blog.onede4.com/java5-thread-concurrent-exchanger/