In multithreaded programming, you often encounter a case where the thread pool is closed. This will use the shutdown and Shutdownnow, which are the two suitable use scenarios?
The individual has tested it:
Scenario One: All threads are a task, are batch jobs, have no relationship to each other, the exception of a thread has little effect on the result. Then all the threads can end normally after the execution of the task, and the program can exit normally after all the tasks have been completed, which is suitable for shutdown.
Scenario Two: All threads are a worker, continuously receiving tasks from the task pool, and the entire task cycle is very long. However, if a thread fails to perform a task, the whole result is a failure, and other workers continue to do the remaining tasks in vain, which requires them to stop their current work. Using Shutdownnow here will allow all threads in the pool to stop the current work, forcing all threads to execute the exit. This allows the main program to exit normally.
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TestShutDown {
public static void main(String[] args) {
try {
testShutDown(100);
testShutDowNow(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void testShutDown(int startNo) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++) {
executorService.execute(getTask(i + startNo));
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.DAYS);
System.out.println("shutDown->all thread shutdown");
}
public static void testShutDowNow(int startNo) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++) {
executorService.execute(getTask(i + startNo));
}
executorService.shutdownNow();
executorService.awaitTermination(1, TimeUnit.DAYS);
System.out.println("shutdownNow->all thread shutdown");
}
public static Runnable getTask(int threadNo) {
final Random rand = new Random();
final int no = threadNo;
Runnable task = new Runnable() {
@Override
public void run() {
try {
System.out.println(no + "-->" + rand.nextInt(10));
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("thread " + no + " has error" + e);
}
}
};
return task;
}
}
Execution Result:
After shutdown, you can use Awaittermination to wait for all threads to finish executing the current task.
Shutdownnow will force all currently executing tasks to stop working.
100-->2
101-->9
102-->0
103-->0
104-->9
shutDown->all thread shutdown
200-->9
201-->8
thread 200 has errorjava.lang.InterruptedException: sleep interrupted
thread 201 has errorjava.lang.InterruptedException: sleep interrupted
shutdownNow->all thread shutdown
The difference between shutdown and Shutdownnow