内容:CountDownLatch允许一个或多个线程等待其他线程完成操作。CountDownLatch的构造函数接收一个int类型的参数作为计数器,如果你想等待N个线程或者说等待N个执行步骤,那么可以将N作为参数传入。当我们调用一次CountDownLatch的countDown方法时,N就会减1,CountDownLatch的await会阻塞当前线程直到N为0。用于多个线程时,你只需要将这个CountDownLatch的引用传递到线程里。
public class CountDownLatchTest { static class Worker implements Runnable { private final CountDownLatch doneSignal; private final int i; public Worker(CountDownLatch doneSignal, int i) { this.doneSignal = doneSignal; this.i = i; } @Override public void run() { System.out.println("now is " + i); doneSignal.countDown(); } } public static void main(String[] args) throws InterruptedException { int N = 10; CountDownLatch countDownLatch = new CountDownLatch(N); ExecutorService executor = Executors.newFixedThreadPool(N); for (int i = 0; i < N; i++) executor.execute(new Worker(countDownLatch, i)); countDownLatch.await(); System.out.println("over"); } }
时间: 2024-10-14 09:40:08