public void testCountDownLatch() {
ThreadFactory factory = new ThreadFactory() {
int i = 1;
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "线程" + i++);
}
};
int size = 10;
final CountDownLatch latch = new CountDownLatch(size);
ExecutorService executor = Executors.newCachedThreadPool(factory);
for (int i = 0; i < size; i++) {
executor.submit(
new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "等待执行");
try {
int time = new Random().nextInt(5);
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println(Thread.currentThread().getName() + "执行完毕");
}
}
);
}
executor.shutdown();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("所有线程执行完毕");
}