jdk1.5的CountDownLatch同步工具

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

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

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

/**
*
* ClassName:CountdownLatchTest
* jdk1.5的CountDownLatch同步工具
*
* 主线程(裁判员发令)先运行(cdOrder.countDown()),其它线程(运动员)等待(裁判发令)(cdAnswer.await())
* 主线程(裁判员发令)完毕后通知其他线程(运动员)运行(cdAnswer.countDown()),主线程(裁判员)等待(运动员)运行结果(cdOrder.await())
* @author songjy
* @version 1.0
* @since v1.0
* @Date 2013-8-26 下午9:34:54
*/
public class CountdownLatchTest {

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

public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch cdOrder = new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
Runnable runnable = new Runnable() {
public void run() {
try {
log.info("线程" + Thread.currentThread().getName()
+ "正准备接受命令");
cdOrder.await();
log.info("线程" + Thread.currentThread().getName()
+ "已接受命令");
Thread.sleep((long) (Math.random() * 10000));
log.info("线程" + Thread.currentThread().getName()
+ "回应命令处理结果");
cdAnswer.countDown();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
};
service.execute(runnable);
}
try {
Thread.sleep((long) (Math.random() * 10000));

log.info("线程" + Thread.currentThread().getName() + "即将发布命令");
cdOrder.countDown();
log.info("线程" + Thread.currentThread().getName() + "已发送命令,正在等待结果");
cdAnswer.await();
log.info("线程" + Thread.currentThread().getName() + "已收到所有响应结果");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
service.shutdown();

}
}


[url=http://zk1878.iteye.com/blog/1002652]java 多线程 CountDownLatch用法[/url]
[url=http://iaiai.iteye.com/blog/2285472]闭锁CountDownLatch与栅栏CyclicBarrier[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值