首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >保存父线程的CountDownLatch

保存父线程的CountDownLatch
EN

Stack Overflow用户
提问于 2021-07-24 04:54:02
回答 1查看 58关注 0票数 1

如何保持主线程,直到所有5个任务(线程)都完成?

代码语言:javascript
复制
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();
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-24 05:04:10

您可以使用CountDownLatchawait方法将线程挂起,直到锁存器达到零。您还需要修改您提交的任务,使其也对闩锁进行倒数。如下所示:

代码语言:javascript
复制
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();
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68504945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档