线程的暂停有两个方法 shutdown 与shutdownNow 两个方法的调用都会阻止新任务的提交,区别是关于已经提交未完成任务的处理已经线程终端的处理,
shutdown会继续执行并且完成所有未执行的任务,shutdownNow 会清楚所有未执行的任务并且在运行线程上调用interrupt() 。
写个例子验证下吧:
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) {
// TODO: handle exception
System.out.println(e.getMessage() + " " + i);
}
if (i == 4){
threadInterupttest.executor.shutdownNow();
}
}
}
class MyRunnable implements Runnable {
public int i;
public MyRunnable(int i) {
// TODO Auto-generated constructor stub
this.i = i;
}
@Override
public void run() {
// TODO Auto-generated method stub
// int a = 0;
// for (double m = 0; m < Integer.MAX_VALUE; m++) {
// a++;
// }
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage()+" "+ i);
}
System.out.println("I am the " + i + " task");
}
}
}
运行结果为
sleep interrupted 1
I am the 1 task
null 5
代码中我们使用了一个单线程的线程池,我们提交给线程池执行的任务是每个任务休眠2秒然后打印一下任务ID
我们使用了一个循环填加5个任务,并且在添加完第4个后终止线程池调用的方法是 shutdownNow()
从打印的结果看 第个任务执行完了,但是接受到了中断异常,而 2,3,4任务并没有执行,第5个任务添加的时候报了
RejectedExecutionException,也就是任务添加被拒绝了。
我们把shutdownNow改成shutDown 看下运行结果:
null 5
I am the 1 task
I am the 2 task
I am the 3 task
I am the 4 task
第5个任务被拒绝了,其他提交的任务都执行了,并且没有收到中断请求!
这也验证了文章开始对两个方法的解释.