Turning an ExecutorService to daemon in Java

后端 未结 8 2275
无人共我
无人共我 2020-11-27 02:39

I am using an ExecutoreService in Java 1.6, started simply by

ExecutorService pool = Executors.newFixedThreadPool(THREADS). 

When my main

8条回答
  •  悲哀的现实
    2020-11-27 03:21

    If you have a known list of tasks, you don't need daemon threads at all. You can simply call shutdown() on the ExecutorService after submitting all your tasks.

    When your main thread is complete, use the awaitTermination() method to allow time for the submitted tasks to complete.The currently submitted tasks will be executed, and the thread pool will terminate its control thread once they have been completed.

    for (Runnable task : tasks) {
      threadPool.submit(task);
    }
    threadPool.shutdown();
    /*... do other stuff ...*/
    //All done, ready to exit
    while (!threadPool.isTerminated()) {
      //this can throw InterruptedException, you'll need to decide how to deal with that.
      threadPool.awaitTermination(1,TimeUnit.SECOND); 
    }
    

提交回复
热议问题