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..."总是等待两个线程完成后打印
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。