ExecutorService's shutdown() doesn't wait until all threads will be finished

前端 未结 3 855
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 07:23

I have a code where 4 threads run at the same time. I want to wait until all these 4 threads will be finished. And only after that to continue the app flow.

I tried

3条回答
  •  一生所求
    2021-01-05 07:53

    Thanks to @Adam Siemion suggestions, here is a final code:

    ExecutorService service = Executors.newFixedThreadPool(cpuCoresNum);
    
    int itNum = 1;
    
    for (int i = 0; i < cpuCoresNum; i++) {
    
        int treadID = itNum++;
    
        service.submit(() -> {
            Thread.currentThread().setName("Thread_#" + treadID);
            try {
                foo();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    
    // wait until all threads will be finished
    service.shutdown();
    try {
        service.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    

提交回复
热议问题