jdk1.5的Exchanger同步工具

package cn.com.songjy.test.socket.thread;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
*
* ClassName:ExchangerTest
* jdk1.5的Exchanger同步工具
*
* 2个线程的数据交换模拟,形象一点的说明就是货物交换
* @author songjy
* @version 1.0
* @since v1.0
* @Date 2013-8-27 下午1:44:45
*/
public class ExchangerTest {

private static Log log = LogFactory.getLog(ExchangerTest.class);

public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final Exchanger exchanger = new Exchanger();
service.execute(new Runnable() {
public void run() {
try {

String data = "[牛]";
System.out.println("线程" + Thread.currentThread().getName()
+ "正在把数据" + data + "换出去");
Thread.sleep((long) (Math.random() * 10000));
String data2 = (String) exchanger.exchange(data);
log.info("线程" + Thread.currentThread().getName() + "换回的数据为"
+ data2);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
});
service.execute(new Runnable() {
public void run() {
try {
String data = "[羊]";
System.out.println("线程" + Thread.currentThread().getName()
+ "正在把数据" + data + "换出去");
Thread.sleep((long) (Math.random() * 10000));
String data2 = (String) exchanger.exchange(data);
log.info("线程" + Thread.currentThread().getName() + "换回的数据为"
+ data2);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
});

service.shutdown();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值