CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了(类似join()方法)。
public class TreadCountDownLatch {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(2);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("我是子线程"+Thread.currentThread().getName()+"开始执行任务...");
try {
Thread.sleep(10);
System.out.println("我是子线程"+Thread.currentThread().getName()+"执行结束...");
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("我是子线程"+Thread.currentThread().getName()+"开始执行任务...");
try {
Thread.sleep(10);
System.out.println("我是子线程"+Thread.currentThread().getName()+"执行结束...");
countDownLatch.countDown();//每次调用减1
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
countDownLatch.await();//阻塞当前线程 ,直到计数为0时,阻塞状态变为运行状态
System.out.println("我是主线程"+Thread.currentThread().getName()+"继续执行...");
}
}
执行结果: