package com.thread.test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(10);
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
newFixedThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
// 模拟执行任务
Thread.sleep(1000);
System.err.println(Thread.currentThread().getName());
// 每执行完一项任务就减1
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
// 等待CountDownLatch中门闩的数量减为0再执行剩下的操作
// 注意:这里是CountDownLatch的await方法,而不是Object的wait方法
latch.await();
System.err.println(Thread.currentThread().getName());
newFixedThreadPool.shutdown();
}
}