ThreadPool shutdown 与shutdownNow
https://blog.csdn.net/liulipuo/article/details/39004279
线程的暂停有两个方法 shutdown 与shutdownNow 两个方法的调用都会阻止新任务的提交,区别是关于已经提交未完成任务的处理已经线程终端的处理:
- shutdown会继续执行并且完成所有未执行的任务,shutdownNow 会清楚所有未执行的任务并且在运行线程上调用interrupt() 。
写个例子验证下吧:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55package com.other.Thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; public class ThreadPoolTest { ExecutorService executor; public static void main(String[] args) { ThreadPoolTest threadInterupttest = new ThreadPoolTest(); threadInterupttest.executor = Executors.newSingleThreadExecutor(); for (int i = 1; i <= 5; i++) { try { threadInterupttest.executor.execute(threadInterupttest.new MyRunnable(i)); } catch (RejectedExecutionException e) { System.out.println(e.getMessage() + " " + i); } if (i == 4) { threadInterupttest.executor.shutdownNow(); } } } class MyRunnable implements Runnable { public int i; public MyRunnable(int i) { this.i = i; } @Override public void run() { // int a = 0; // for (double m = 0; m < Integer.MAX_VALUE; m++) { // a++; // } try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println(e.getMessage() + " " + i); } System.out.println("I am the " + i + " task"); } } }
运行结果为 :
复制代码
1
2
3
4sleep interrupted 1 I am the 1 task null 5
- 代码中我们使用了一个单线程的线程池,我们提交给线程池执行的任务是每个任务休眠2秒然后打印一下任务ID,我们使用了一个循环填加5个任务,并且在添加完第4个后终止线程池调用的方法是 shutdownNow(),从打印的结果看 第个任务执行完了,但是接受到了中断异常,而 2,3,4任务并没有执行,第5个任务添加的时候报了RejectedExecutionException,也就是任务添加被拒绝了。
我们把shutdownNow改成shutDown 看下运行结果:
复制代码
1
2
3
4
5
6null 5 I am the 1 task I am the 2 task I am the 3 task I am the 4 task
第5个任务被拒绝了,其他提交的任务都执行了,并且没有收到中断请求!
这也验证了文章开始对两个方法的解释。
最后
以上就是迷你香水最近收集整理的关于《转载》 ThreadPool shutdown 与shutdownNow的全部内容,更多相关《转载》 内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复