shutdown and awaitTermination which first call have any difference?

前端 未结 9 1188
渐次进展
渐次进展 2020-12-12 14:44

What is the difference between

ExecutorService eService = Executors.newFixedThreadPool(2);
eService.execute(new TestThread6());
eService.execute(new TestThre         


        
9条回答
  •  [愿得一人]
    2020-12-12 15:10

    From Java8 ThreadPool awaitTermination method:

        try {
            for (;;) {
                if (runStateAtLeast(ctl.get(), TERMINATED))
                    return true;
                if (nanos <= 0)
                    return false;
                nanos = termination.awaitNanos(nanos);
            }
        } finally {
            mainLock.unlock();
        }
    

    It will first check run state of thread pool. And if the thread pool is not shut down(which set run state to terminated), awaitTermination method will not return until timeout. This explains why await a long time if you await first then shutdown.

提交回复
热议问题