10 CountDownLatch
public CountDownLatch(int count) {}; // 参数 count 为计数值
public void await() throws InterruptedException {}; // 调用 await() 方法的线程会被挂起,它会等待直到 count 值为 0 才继续执行
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {}; // 和 await() 类似,只不过等待一定的时间后 count 值还没变为 0 的话就会继续执行
public void countDown() {}; // 将 count 值减 1public class T {
public static void main(String[] args) throws InterruptedException {
final int size = 5;
CountDownLatch countDownLatch = new CountDownLatch(size);
for (int i = 0; i < size; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " start");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " end");
countDownLatch.countDown();
}, "Thread" + i).start();
}
System.out.println("main thread await");
countDownLatch.await();
System.out.println("main thread finishes await");
}
}最后更新于