以下是main函数中的代码,想测试一下shutdownNow的效果。
public class TestLa { public static void main(String... args){ /*省略了一段无意义的测试代码*/ ExecutorService executorService = Executors.newFixedThreadPool(2); class Task implements Callable<Integer> { public int id; Task(int id) { this.id = id; } @Override public Integer call() throws Exception { System.out.println(String.format("我的id是:%s,开始计算>>>...",id)); int sum = 0; for(int i = 0; i < 100; i++){ sum += i; Thread.sleep(100); } System.out.println(String.format("我的id是:%s,执行结束>>>...",id)); return sum; } } Future<Integer> future = executorService.submit(new Task(1)); executorService.submit(new Task(2)); executorService.submit(new Task(3)); executorService.submit(new Task(4)); List<Runnable> tasksWaitExecutingList = executorService.shutdownNow(); System.out.println("我们在执行器结束时未完成:"); for(Runnable item : tasksWaitExecutingList) { Thread thisThread = new Thread(item); thisThread.start(); } /*executorService.shutdown();*/ try { System.out.println("计算结果:"+ future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
程序运行的结果:
我们在执行器结束时未完成: 我的id是:3,开始计算>>>... 我的id是:1,开始计算>>>... 我的id是:2,开始计算>>>... 我的id是:4,开始计算>>>... java.util.concurrent.ExecutionException: java.lang.InterruptedException: sleep interrupted at java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.util.concurrent.FutureTask.get(FutureTask.java:188) at com.mq.xx.entrust.action.TestLa.main(TestLa.java:137) Caused by: java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at com.mq.xx.entrust.action.TestLa$1Task.call(TestLa.java:116) at com.mq.xx.entrust.action.TestLa$1Task.call(TestLa.java:1) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 我的id是:4,执行结束>>>... 我的id是:3,执行结束>>>...
不知道主线程退出怎么中断了其他线程的,这里调用 future.get() 并不会阻塞主线程。而运行executorService.shutdown(),而不是shutdownNow的时候,程序不会抛出异常,主线程会阻塞到future.get()有返回的时候,不太明白
欧阳克2016-11-19 15:26:36
就应该是这个效果呀,shutdownNow的doc
There are no guarantees beyond best-effort attempts to stop processing
actively executing tasks. For example, typical implementations will
cancel via Thread.interrupt, so any task that fails to respond to
interrupts may never terminate.
线程调用interrupt如果正在sleep就会抛出这个异常。和future并没有什么关系。具体的你可以看看ExecutorService的实现呀。
三叔2016-11-19 15:25:53
shutdownNow是立即退出,不管有没有执行完毕,所以会报InterruptedException。
shutdown是会等到执行完毕再退出,所有不会有异常。