共计 1258 个字符,预计需要花费 4 分钟才能阅读完成。
CountDownLatch 介绍
CountDownLatch 类位于 java.util.concurrent 包下,利用它可以实现类似计数器的功能。比如有一个任务 A,它要等待其他几个任务执行完毕之后才能执行,此时就可以利用 CountDownLatch 来实现这种功能了。CountDownLatch 是通过一个计数器来实现的,计数器的初始值为线程的数量。每当一个线程完成了自己的任务后,计数器的值就会减 1。当计数器值到达 0 时,它表示所有的线程已经完成了任务,然后在闭锁上等待的线程就可以恢复执行任务。
定义两个线程
- 线程 1
public class Thread1 extends Thread {
private CountDownLatch countDownLatch;
public Thread1(CountDownLatch countDownLatch) {this.countDownLatch = countDownLatch;}
@Override
public void run() {
try {Thread.sleep(5000);
} catch (InterruptedException e) {e.printStackTrace();
}
System.out.println("thread-1");
countDownLatch.countDown();}
}
- 线程 2
public class Thread2 extends Thread {
private CountDownLatch countDownLatch;
public Thread2(CountDownLatch countDownLatch) {this.countDownLatch = countDownLatch;}
@Override
public void run() {
try {Thread.sleep(5000);
} catch (InterruptedException e) {e.printStackTrace();
}
System.out.println("thread-2");
countDownLatch.countDown();}
}
请求
@RequestMapping("test-countdownlatch")
public void testCountDownLatch() {CountDownLatch countDownLatch = new CountDownLatch(2);
Thread1 thread1 = new Thread1(countDownLatch);
Thread2 thread2 = new Thread2(countDownLatch);
thread1.start();
thread2.start();
try {countDownLatch.await();
System.out.println("main...");
} catch (InterruptedException e) {e.printStackTrace();
}
}
结果
“main…” 总是等待两个线程完成后打印
CountDownLatch 代码
正文完