如何等到线程池中的所有作业都完成?
How to wait until all jobs are finished in thread pool?
我有一个线程池,请看下面的代码。我现在想要的是 before asserEquals 语句等待所有作业完成。如何实现? awaitTermination() 仅在已调用关机时才有效,但这不是我想要的。
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();
}
// 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 并计数直到线程完成。
它的问题是,即使在您开始 "count down" 之后,理论上一些其他线程也可以添加到池中,这就是为什么通常您关闭以便以后无法添加其他作业的原因。
尝试使用 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();
}
我有一个线程池,请看下面的代码。我现在想要的是 before asserEquals 语句等待所有作业完成。如何实现? awaitTermination() 仅在已调用关机时才有效,但这不是我想要的。
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();
}
// 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 并计数直到线程完成。 它的问题是,即使在您开始 "count down" 之后,理论上一些其他线程也可以添加到池中,这就是为什么通常您关闭以便以后无法添加其他作业的原因。
尝试使用 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();
}