The shutdownNow()
method is used to shut down the executor service abruptly. This method tries to stop all jobs that are now running, pauses the processing of tasks that are waiting to be executed, and delivers a list of the tasks that were waiting.
List<Runnable> shutdownNow()
The method takes no parameters.
This method returns a list of jobs that were awaiting execution.
import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;public class Main{public static void main(String[] args) {final ExecutorService threadPool = Executors.newFixedThreadPool(10);for (int i = 0; i < 100; i++) {threadPool.execute(() -> {if (threadPool.isShutdown()) {System.out.println("Pool is terminating.");}try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {System.out.println("WARN: Task interrupted");}System.out.println("Doing work.");});}final List<Runnable> awaitingTasks = threadPool.shutdownNow();System.out.println("The list of awaiting tasks are:" + awaitingTasks);}}
10
threads.for
loop, we submit runnables to the thread pool. The runnable does the following:
Pool is terminating.
WARN: Task interrupted.
Doing work.
is printed to indicate that the task/runnable is executing.shutdownNow()
method on the executor service or thread pool. The tasks awaiting execution are stored in the awaitingTasks
list.awaitingTasks
list.