CountDownLatch 持有父线程

CountDownLatch to hold the parent thread

如何保持主线程直到所有 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();
        }

您可以使用 CountDownLatchawait 方法来阻止线程直到闩锁达到零。您还需要修改您提交的任务以对闩锁进行倒计时。像这样:

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();
}