简体   繁体   中英

Difference between executor terminate and shutdown

I want to wait for ALL my threads to be executed and only then continue.

ExecutorService es = Executors.newFixedThreadPool(3);
List<Callable<Void>> calls = new LinkedList<>();

Arrays.stream(new int[]{1,2,3})
        .forEach( i -> calls.add(() -> {
            someFunc(i);
            return null;
        }));

try {
    es.invokeAll(calls);
} catch (InterruptedException e) {
    e.printStackTrace();
}

es.shutdown();

System.out.println(es.isTerminated()); //prints false
System.out.println(es.isShutdown()); //prints true

why I don't get true for both cases ?

all my threads have been successfully terminated.

Looking into the documentation of isTerminated highlights the difference:

Returns true if all tasks have completed following shut down. Note that isTerminated() is never true unless either shutdown() or shutdownNow() was called first.

@return true if all tasks have completed following shut down

So in your case, it means that the executor was shut down but your tasks did not complete.

instead of using shutdown, you may use thread.join for waiting to all thread has done to shutdown later with normal thread. In your case, using ExecutorService, after shutdown, you need to execute taskExecutor.awaitTermination to waiting for the other task have not done yet.

try {
  es.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
  ...
}

The shutdown process for a thread executor involves first rejecting any new tasks submitted to the thread executor while continuing to execute any previously submitted tasks. During this time, calling isShutdown() will return true, while isTerminated() will return false.

Since you called es.shutDown() , es.isShutdown() returns true. But by the time you reach es.isTerminated() the tasks started by es.invokeAll(calls) are still being executed. Therefor isTerminated() returns false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM