系列文章目录
前言
前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。
CountDownLatch
CountDownLatch是一个同步工具类,它允许一个或多个线程等待其他线程一系列操作的完成。
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
我们来看两个示例
@Test
public void CountDownLatchTest1() throws Exception {
// 这里只有一个计数器,子线程都要等待主线程释放这个计数器才会开始执行,子任务等核心任务
CountDownLatch countDownLatch = new CountDownLatch(1);
for (int i = 1; i <= 3; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "准备好了");
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "开始奔跑");
}, String.valueOf(i) + "号运动员\t").start();
}
System.out.println("运动员们进场");
//睡眠,保证所有子线程创建完毕都进入run方法,执行await()方法
Thread.sleep(500);
System.out