CountDownLatch:
CountDownLatch.java类中定义的构造函数:
1
2
|
//Constructs a CountDownLatch initialized with the given count.
public
void
CountDownLatch(
int
count) {...}
|
构造器中的计数值(count)实际上就是闭锁需要等待的线程数量。这个值只能被设置一次,而且CountDownLatch没有提供任何机制去重新设置这个计数值。
与CountDownLatch的第一次交互是主线程等待其他线程。主线程必须在启动其他线程后立即调用CountDownLatch.await()方法。这样主线程的操作就会在这个方法上阻塞,直到其他线程完成各自的任务。
package com;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchDemo implements Runnable {
static final CountDownLatch end = new CountDownLatch(10);
static final CountDownLatchDemo demo = new CountDownLatchDemo();
public void run() {
System.out.println("执行业务逻辑完成 end...");
end.countDown();
}
public static void main(String[] args) throws InterruptedException {
ExecutorService exec = Executors.newFixedThreadPool(10);
for(int i=1;i<=10;i++){
exec.submit(demo);
}
/**
* 执行等待操作
*/
end.await();
System.err.println("fire");
exec.shutdown();//主线程操作
}
}