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

前端 未结 3 858
被撕碎了的回忆
被撕碎了的回忆 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:58

    Recommended way from oracle documentation page of ExecutorService:

     void shutdownAndAwaitTermination(ExecutorService pool) {
       pool.shutdown(); // Disable new tasks from being submitted
       try {
         // Wait a while for existing tasks to terminate
         if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
           pool.shutdownNow(); // Cancel currently executing tasks
           // Wait a while for tasks to respond to being cancelled
           if (!pool.awaitTermination(60, TimeUnit.SECONDS))
               System.err.println("Pool did not terminate");
         }
       } catch (InterruptedException ie) {
         // (Re-)Cancel if current thread also interrupted
         pool.shutdownNow();
         // Preserve interrupt status
         Thread.currentThread().interrupt();
       }
    

    shutdown(): Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

    shutdownNow():Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

    In above example, if your tasks are taking more time to complete, you can change if condition to while condition

    Replace

    if (!pool.awaitTermination(60, TimeUnit.SECONDS))
    

    with

     while(!pool.awaitTermination(60, TimeUnit.SECONDS)) {
         Thread.sleep(60000);
     }  
    

提交回复
热议问题