java全部线程完成后再执行
程序员文章站
2022-06-12 21:11:43
...
import java.util.concurrent.CountDownLatch; public class Driver { // ... public static void main(String[] args) throws InterruptedException { int N = 10; CountDownLatch startSignal = new CountDownLatch(1); CountDownLatch doneSignal = new CountDownLatch(N); for (int i = 0; i < N; ++i) { // create and start threads new Thread(new Worker(startSignal, doneSignal)).start(); } System.out.println("don't let run yet"); // don't let run yet startSignal.countDown(); // let all threads proceed // System.out.println("startSignal.countDown()ed"); doneSignal.await(); // wait for all to finish System.out.println("main down"); } } class Worker implements Runnable { private final CountDownLatch startSignal; private final CountDownLatch doneSignal; Worker(CountDownLatch startSignal, CountDownLatch doneSignal) { this.startSignal = startSignal; this.doneSignal = doneSignal; } public void run() { try { startSignal.await(); doWork(); doneSignal.countDown(); } catch (InterruptedException ex) { } // return; } void doWork() { System.out.println("doWork"); } }