在多线程编程中,经常会遇到将线程池关闭的case。这就会使用到ShutDown和ShutDownNow,这两者到底适合哪种使用场景呢?
个人对其进行了一番测试:
场景一:所有线程都是一个task,都是批处理作业,相互之间没有什么关系,某个线程的异常对结果影响不大。那么所有线程都能在执行任务结束之后可以正常结束,程序能在所有task都做完之后正常退出,适合用ShutDown。
场景二:所有线程都是一个工人,源源不断的从任务池中接收任务,整个任务周期非常长。但是,如果一个线程在做某个任务的时候失败,则整个结果就是失败的,其他worker再继续做剩下的任务也是徒劳,这就需要让他们全部停止当前的工作。这里使用ShutDownNow就可以让该pool中的所有线程都停止当前的工作,从而迫使所有线程执行退出。从而让主程序正常退出。
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; } }
执行结果:
shutDown后可以使用awaitTermination等待所有线程执行完毕当前任务。
shutDownNow就会迫使当前执行的所有任务停止工作。
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
时间: 2024-11-05 02:29:16