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();
}
}
jdk1.5的Exchanger同步工具
最新推荐文章于 2021-09-23 11:29:13 发布