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

多线程的同步工具(CountDownLatch)

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

标签:strong   rgs   test   1.0   调用   百度   ...   runnable   com   

public class CountDownLatchextends Object

一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。如果需要重置计数,请考虑使用 CyclicBarrier

事例代码:

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

/**
* 线程记时器
*
* @author wangyi
* @verion 1.0 <br />
* <a href="www.baidu.com">百度一下</a>
*/
public class CountDownLatchTest {
public static void main(String[] args) {
ExecutorService threadpool = Executors.newCachedThreadPool();
final CountDownLatch cdh1 = new CountDownLatch(1);
final CountDownLatch cdh2 = new CountDownLatch(3);
for (int i = 1; i <= 3; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()
+ "正在等待命令:");
cdh1.await();
Thread.sleep((int) (Math.random() * 10000));
System.out.println(Thread.currentThread().getName()
+ "结果处理中...");
Thread.sleep((int) (Math.random() * 10000));
System.out.println(Thread.currentThread().getName()
+ "任务已完成");
cdh2.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
};
threadpool.execute(runnable);
}
try {
Thread.sleep((int) (Math.random() * 10000));
System.out.println(Thread.currentThread().getName()
+ "开始发布任务,等待接收结果...");
cdh1.countDown();

cdh2.await();
System.out.println(Thread.currentThread().getName() + "结果已得到");
} catch (Exception e) {
e.printStackTrace();
}
threadpool.shutdown();
}

}

多线程的同步工具(CountDownLatch)

标签:strong   rgs   test   1.0   调用   百度   ...   runnable   com   

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

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