The difference between the shutdown() and shutdownNow() methods in the thread pool

The difference between the shutdown() and shutdownNow() methods in the thread pool

Under normal circumstances, when we frequently use threads, in order to save resources and quickly respond to needs, we will consider using the thread pool. After the thread pool is used, we will think about closing it. When shutting down, shutdown and shutdownNow are generally used. Both functions can be used to close the thread pool, so what is the difference between them? Next, I will use one sentence to understand the difference between shutdown and shutdownNow.

1. Explain the difference between shutdown and shutdownNow in one sentence

Shutdown just sets the state of the thread pool to SHUTWDOWN state, and the tasks being executed will continue to be executed, and those that are not executed will be interrupted.

And shutdownNow is to set the state of the thread pool to STOP, the tasks being executed are stopped, and the tasks that are not executed are returned.

Let’s take an example of workers eating steamed buns. Workers in a factory are eating steamed buns (which can be understood as a task). The buns in the cage in your hand cannot be eaten! And if they receive the shutdownNow order, these workers will stop eating buns immediately, and they will put down the unfinished buns on hand, let alone the buns in the cage.

1、shutDown()

When the thread pool calls this method, the state of the thread pool immediately changes to the SHUTDOWN state. At this point, no more tasks can be added to the thread pool, otherwise a RejectedExecutionException will be thrown. However, the thread pool will not exit immediately at this time, and will not exit until the tasks added to the thread pool have been processed.

2、shutdownNow()

Executing this method, the state of the thread pool immediately changes to STOP state, and tries to stop all executing threads, no longer processing tasks still waiting in the pool queue , of course, it will return those unexecuted tasks. It tries to terminate the thread by calling the Thread.interrupt() method, but as we all know, this method has limited effects. If there are no sleep, wait, Condition, time lock and other applications in the thread, the interrupt() method is Unable to interrupt the current thread. Therefore, ShutdownNow() does not mean that the thread pool will be able to exit immediately, it may have to wait for all executing tasks to complete before exiting.

 

 

 

 

Guess you like

Origin blog.csdn.net/QRLYLETITBE/article/details/129308587