首页 > 代码库 > 多线程的同步工具(CountDownLatch)

多线程的同步工具(CountDownLatch)

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="http://www.mamicode.com/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)