CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。
这里举个例子:
比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了。
代码如下:
package com.newDemo.controller.test;
import java.util.concurrent.CountDownLatch;
public class threadDemo21 {
public static void main(String[] args) throws InterruptedException {
System.out.println("等待子线程执行完毕...");
final CountDownLatch countDownLatch = new CountDownLatch(2);
Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println("子线程," + Thread.currentThread().getName() + "开始执行...");
countDownLatch.countDown();// 每次减去1
System.out.println("子线程," + Thread.currentThread().getName() + "结束执行...");
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
public void run() {
System.out.println("子线程," + Thread.currentThread().getName() + "开始执行...");
countDownLatch.countDown();// 每次减去1
System.out.println("子线程," + Thread.currentThread().getName() + "结束执行...");
}
});
t2.start();
countDownLatch.await();// 调用当前方法主线程阻塞 countDown结果为0, 阻塞变为运行状态
System.out.println("两个子线程执行完毕....");
System.out.println("继续主线程执行..");
}
}
执行大结果如下:
这里就可看出来,首先去执行2个子线程,最后才会执行主线程。
总结:countDownLatch.countDown();// 每次减去1
countDownLatch.await();// 调用当前方法主线程阻塞 countDown结果为0, 阻塞变为运行状态
来源:CSDN
作者:努力努力再努力@x
链接:https://blog.csdn.net/qq_35657661/article/details/103615252