如何保持主线程,直到所有5个任务(线程)都完成?
class ReadMessages {
private final ExecutorService executorService = Executors.newFixedThreadPool(5);
void readMessage(List<Messages> msg )
{
CountDownLatch latch = new CountDownLatch(msg.size); /// lets say msg.size()=5
for( Messages m : msg) {
executorService.submit(() -> dbservice.processInDB(message)); //execute saveInDb paaralllely in 5 different threads
}
//Hold the main thread until all 5 threads have completed their work. i.e make latch count to 0
//then send email
emailService();
}发布于 2021-07-24 05:04:10
您可以使用CountDownLatch的await方法将线程挂起,直到锁存器达到零。您还需要修改您提交的任务,使其也对闩锁进行倒数。如下所示:
void readMessage(List<Messages> msg) {
CountDownLatch latch = new CountDownLatch(msg.size); /// lets say msg.size()=5
for(Messages m : msg) {
executorService.submit(() -> {
try {
dbservice.processInDB(m); //execute saveInDb paaralllely in 5 different threads
} finally {
// One of the messages has been processed, count down the latch by 1
latch.countDown();
}
});
}
//Hold the main thread until all 5 threads have completed their work. i.e make latch count to 0
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
//then send email
emailService();
}https://stackoverflow.com/questions/68504945
复制相似问题