ThreadPool shutdown 与shutdownNow

本文通过示例代码对比了Java线程池中shutdown与shutdownNow方法的区别。shutdown允许已提交的任务完成,而shutdownNow尝试取消正在运行的任务并停止接受新任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程的暂停有两个方法 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个任务被拒绝了,其他提交的任务都执行了,并且没有收到中断请求!

这也验证了文章开始对两个方法的解释.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值