Java多线程ExecutorService.shutdown什么时候执行

原文链接4L大神

 

主线程和线程池之间没有直接关系,线程池使用自己的线程。生命周期也相互独立。

shutdown()可以理解为:主线程要求线程池关闭,但不会为此等待线程池执行完毕。

 

shutdown() 作为函数,当然是立即执行,也即是不再接受新任务了;但是它既不会强行终止正在执行的任务,也不会取消已经提交的任务。也就是说之前提交的5个任务,仍然会执行完毕,且跟主线程生命周期无关,也就是即便你直接在后面写上: if (1==1) return; 来立即结束主函数,你也会发现线程池的5个任务会顺利执行完毕。


另一个长得很像的函数是:
shutdownNow(),这个函数比shutdown()更狠,两点:
1、对于尚未执行的任务,全部取消掉;
2、对于正在执行的任务,发出interrupt()。
不过你的程序因为在发生异常时没有正确释放信号量,所以如果改为shutdownNow()会出问题:主线程死等。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package 操作系统实验二; import java.util.concurrent.*; class PrintTask implements Runnable { private char ch; private Semaphore currentSemaphore; private Semaphore nextSemaphore; public PrintTask(char ch, Semaphore currentSemaphore, Semaphore nextSemaphore) { this.ch = ch; this.currentSemaphore = currentSemaphore; this.nextSemaphore = nextSemaphore; } public void run() { try { for (int i = 0; i < 3; i++) { currentSemaphore.acquire(); System.out.print(ch); nextSemaphore.release(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class Main { public static void main(String[] args) { Semaphore semaphoreA = new Semaphore(1); Semaphore semaphoreB = new Semaphore(0); PrintTask printA = new PrintTask('A', semaphoreA, semaphoreB); PrintTask printB = new PrintTask('B', semaphoreB, semaphoreA); ExecutorService executorService = Executors.newFixedThreadPool(2); // 顺序1:AAAB executorService.execute(printA); executorService.execute(printA); executorService.execute(printA); executorService.execute(printB); // 顺序2:BBAA //executorService.execute(printB); //executorService.execute(printB); //executorService.execute(printA); //executorService.execute(printA); // 顺序3:AABA //executorService.execute(printA); //executorService.execute(printA); //executorService.execute(printB); //executorService.execute(printA); // 顺序4:ABAA //executorService.execute(printA); //executorService.execute(printB); //executorService.execute(printA); //executorService.execute(printA); executorService.shutdown(); } }
06-01

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值