CountDownLatch可以使一个或多个线程等待其他线程各自执行完毕后再执行
class WorkThread implements Runnable { private CountDownLatch countDownLatch; public WorkThread(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 干活结束"); this.countDownLatch.countDown(); } }
package com.demo.atomic; import java.util.concurrent.CountDownLatch; public class countDownLatchDemo { public static void main(String[] args) { // 初始化等待线程个数: 2个 CountDownLatch countDownLatch = new CountDownLatch(2); WorkThread workThread1 = new WorkThread(countDownLatch); WorkThread workThread2 = new WorkThread(countDownLatch); new Thread(workThread1).start(); new Thread(workThread2).start(); // 阻塞主线程,等待子线程全部结束继续 try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("结束了"); } }
如果不等待,执行结果
结束了 Thread-0 干活结束 Thread-1 干活结束
如果等待, 执行结果
Thread-1 干活结束 Thread-0 干活结束 结束了