【问题标题】:How to wait until all jobs are finished in thread pool?如何等到线程池中的所有作业都完成?
【发布时间】:2016-05-16 16:13:03
【问题描述】:
我有一个线程池,请看下面的代码。我现在想要的是 在 asserEquals 语句之前等待所有工作完成。如何做到这一点? awaitTermination() 仅在已调用 shutdown 时才有效,但这不是我想要的。
private volatile int i = 0;
@Test
public void threadPoolTest() throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(8);
threadPool.submit(new Runnable() {
public void run() {
i++;
}
});
threadPool.submit(new Runnable() {
public void run() {
i++;
}
});
assertEquals(2,i);
threadPool .shutdown();
}
【问题讨论】:
标签:
java
multithreading
threadpool
executorservice
【解决方案1】:
// tell the threadpool it shouldn't accept new tasks:
threadPool.shutdown();
// and wait until the already submitted tasks finish:
try {
threadPool.awaitTermination(...);
assertEquals(2,i);
} catch(InterruptedException e) {
assertTrue(false); // shouldn't get here only if timeouts
}
如果您不想提前关闭池,那么您可以使用CountDownLatch 并计数直到线程完成。
问题在于,理论上,即使在您开始“倒计时”之后,其他一些线程也可以添加到池中,这就是为什么通常您会关闭以便以后无法添加其他作业。
【解决方案2】:
尝试使用 CountDownLatch :它是一个可以像计数器一样等待 N 个任务的并发屏障:
@Test
public void threadPoolTest() throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(8);
final CountDownLatch latch = new CountDownLatch(2);
threadPool.submit(new Runnable() {
public void run() {
i++;
latch.countDown();
}
});
threadPool.submit(new Runnable() {
public void run() {
i++;
latch.countDown();
}
});
latch.await();
assertEquals(2,i);
threadPool .shutdown();
}