CountDownLatch 的作用: 能够使一个线程等待其他线程完成各自的工作后再执行.
这里实现的是主线程等待子线程跑完才继续执行.
下面是存在问题的代码片段:
@Test
public void test2() throws InterruptedException {
int threadNum = 5;
AtomicInteger atomic = new AtomicInteger();
Executor executor = Executors.newFixedThreadPool(threadNum);
CountDownLatch latch = new CountDownLatch(200);
for(int i=0;i<20;i++) {
executor.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread thread = Thread.currentThread();
System.out.println(String.format("thread id %s , thread name : %s . start", thread.getId(),
thread.getName()));
} catch (Exception e) {
// TODO: handle exception
} finally {
atomic.incrementAndGet();
latch.countDown();
}
}
});
}
latch.await();
System.out.println(String.format("thread is running off ,latch of count is %s , atomic = %s ",latch.getCount(),atomic.get()));
}
代码的逻辑是: 线程池的容量为5个, 实际线程执行数为20次 , 测试在多线程环境下 AtomicInteger 是否线程安全. 在这里面利用了CountDownLatch 线程等待api .
但CountDownLatch 初始化的数量为200 , 导致主线程一直被挂起.
原因: 当线程执行次数到20次时, 子线程执行已经执行完了, 但CountDownLatch.getCount() 此时还剩下180.
也就是说countDown 执行的次数一定要保证与CountDownLatch初始化的值一致. 才不会导致线程一直挂住.