某些情况下,需要等所有线程的工作全部完成了才继续。这时候CountDownLatch就派上了用场。
public static void main(String[] args) throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(2);
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getId() + " -- " + i);
}
countDownLatch.countDown();
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getId() + " -- " + i);
}
countDownLatch.countDown();
}
}).start();
countDownLatch.await();
System.out.println("end....");
}
在上面的demo中,必须要在两个线程都执行完成之后才会出现end。