java CountDownLatch的使用
CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成了任务,然后在CountDownLatch上等待的线程就可以恢复执行任务。类似join()的作用,join()也可以实现等待一些线程的完成,再执行后面线程。
CountDownLatch 例子:
package com.hts;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchTest {
class Task1 implements Runnable{
CountDownLatch countDownLatch;
Task1(CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
System.out.println("任务1执行了");
countDownLatch.countDown();
}
}
class Task2 implements Runnable{
CountDownLatch countDownLatch;
Task2(CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
System.out.println("任务2执行了");
countDownLatch.countDown();
}
}
class Task3 implements Runnable{
CountDownLatch countDownLatch;
Task3(CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
System.out.println("任务3执行了");
countDownLatch.countDown();
}
}
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(3);
ExecutorService executorService = Executors.newFixedThreadPool(3);
System.out.println("任务开始执行");
executorService.submit(new CountDownLatchTest().new Task1(countDownLatch));
executorService.submit(new CountDownLatchTest().new Task2(countDownLatch));
executorService.submit(new CountDownLatchTest().new Task3(countDownLatch)); //位置①
try {
countDownLatch.await();
System.out.println("三个任务执行完");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
执行结果:
如果把位置①的那行代码注释掉,使得计数器CountDownLatch无法减到0,则会一直阻塞着,等待减到0.
结果如下: