What is the difference between
ExecutorService eService = Executors.newFixedThreadPool(2); eService.execute(new TestThread6()); eService.execute(new TestThread6()); eService.execute(new TestThread6()); eService.awaitTermination(1, TimeUnit.NANOSECONDS); eService.shutdown();
and
eService.shutdown(); eService.awaitTermination(1, TimeUnit.NANOSECONDS);
I don't really understand shutdown()
. This method does not wait for previously submitted tasks to complete execution. Does it mean shutdown()
may terminate the tasks which have been submitted, but not completed? I tried some examples, they do not prove it, please give me an example.
shutdown() will just tell the executor service that it can't accept new tasks, but the already submitted tasks continue to run. shutdownNow() will do the same AND will try to cancel the already submitted tasks by interrupting the relevant threads.
The awaitTermination method of ExecutorService in Java is used to wait for all the tasks submitted to the service to complete execution: After the shutdown of the service was initiated. The wait time for the termination of the service is over. The current thread of execution is interrupted.
ExecutorService is a JDK API that simplifies running tasks in asynchronous mode. Generally speaking, ExecutorService automatically provides a pool of threads and an API for assigning tasks to it.
You should call shutdown
first. Otherwise, you might be waiting for a very long time, since awaitTermination
doesn't actually shut down your executor.
If you wanted to wait for tasks to complete, rather than wait for the executor to shut down, then you should use invokeAll
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With