CountDownLatch相关API
JDK相关解释
一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
用给定的计数 初始化 CountDownLatch
。由于调用了 countDown()
方法,所以在当前计数到达零之前,await
方法会一直受阻塞。之后,会释放所有等待的线程,await
的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。如果需要重置计数,请考虑使用 CyclicBarrier
。
下面是一个Demo
package test.Threae;
import java.util.concurrent.CountDownLatch;
/**
*
* @author wzn
*
*/
public class CountDownLatchDemo {
static CountDownLatch downLatch = new CountDownLatch(2);
public static void main(String[] args) {
new Thread(new Workers("worker1",downLatch, 5000)).start();
new Thread(new Workers("worker2",downLatch, 8000)).start();
try {
downLatch.await();
System.out.println("work over ");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Workers implements Runnable{
private final String workerName;
private final CountDownLatch downLatch;
private final int time;
public Workers(String workerName, CountDownLatch downLatch,int time){
this.downLatch= downLatch;
this.time = time;
this.workerName= workerName;
}
@Override
public void run() {
System.out.println(workerName+"work start");
doWorking();
System.out.println(workerName+"work end bye");
downLatch.countDown();
}
private void doWorking() {
System.out.println("do working");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
也就是说主线程在等待所有其它的子线程完成后再往下执行