以下是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,執(zhí)行結束>>>...",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("我們在執(zhí)行器結束時未完成:");
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();
}
}
}
程序運行的結果:
我們在執(zhí)行器結束時未完成:
我的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,執(zhí)行結束>>>...
我的id是:3,執(zhí)行結束>>>...
不知道主線程退出怎么中斷了其他線程的,這里調用 future.get() 并不會阻塞主線程。而運行executorService.shutdown(),而不是shutdownNow的時候,程序不會拋出異常,主線程會阻塞到future.get()有返回的時候,不太明白
2 回答

jeck貓
TA貢獻1909條經驗 獲得超7個贊
就應該是這個效果呀,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
的實現呀。

幕布斯6054654
TA貢獻1876條經驗 獲得超7個贊
shutdownNow
是立即退出,不管有沒有執(zhí)行完畢,所以會報InterruptedException
。shutdown
是會等到執(zhí)行完畢再退出,所有不會有異常。
添加回答
舉報
0/150
提交
取消