CountDownLatch允许一个或者多个线程去等待其他线程完成操作。
public CountDownLatch(int count) 构造一个使用给定计数初始化的 CountDownLatch
await()
使当前线程等待直到锁存器倒计时到零,除非线程被中断。
如果当前计数为零,则此方法立即返回。
如果当前计数大于零,则当前线程出于线程调度目的而被禁用并处于休眠状态,直到发生以下两种情况之一:
由于调用 countDown 方法,计数达到零;
或其他一些线程中断当前线程。
如果当前线程:
在进入此方法时设置了其中断状态;
或在等待时被打断然后抛出 InterruptedException 并清除当前线程的中断状态。
如果经过指定的等待时间,则返回值 false。
如果时间小于或等于零,则该方法根本不会等待。
countDown()
减少锁存器的计数,如果计数达到零,则释放所有等待线程。如果当前计数大于零,则递减。如果新计数为零,则重新启用所有等待线程以进行线程调度。如果当前计数为零,则不会发生任何事情。
getCount()
返回当前计数。此方法通常用于调试和测试目的。
Demo
public class CountDownLatch_learn {
public static void main(String[] args) {
// 让2个线程去等待2个三个工作线程执行完成
final CountDownLatch latch = new CountDownLatch(2);
ExecutorService executorService = Executors.newFixedThreadPool(3);
Thread thread = new Thread(() -> {
System.out.println("1111 continue running1...");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
latch.countDown();
System.out.println("1111 continue running2...");
});
// executorService.submit(thread);
Thread thread2 = new Thread(() -> {
System.out.println("2222 continue running1...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
latch.countDown();
System.out.println("2222 continue running2...");
});
// executorService.submit(thread2);
System.out.println("3333 continue running2...");
thread.start();
thread2.start();
Runnable runnable = () -> {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("777 continue running2...");
}
System.out.println("4444 continue running2...");
// executorService.shutdown();
System.out.println("5555 continue running2...");
};
new Thread(runnable).start();
}
}