java 带有循环以及等待的线程中断 interrupt()后的情况总结

最近弄一个自定义的线程池,发现main线程运行完后程序还行运行,原因是线程池里面的每个线程还在循环等待下一个任务。想着弄一个关闭线程池的方法使得程序结束,查阅网上文章和实验发现interrupt()执行后的一些情况,在这总结一下。

这里并不是介绍中断线程的方法,中断线程的方法可以见一下另一位作者的:Java中的线程中断。本文也是根据其中常用的interrupt+isInterrupt的方法来中断 带有循环以及等待 的线程的个人知识总结。

一、线程的状态

本文必须了解线程的状态,见另一位作者的java线程状态(六种&五种)。六种和五种区别是在阻塞的概念范围,例如上面介绍中断的方法中所说的“阻塞”便是五种状态而言的。

二、在API中介绍interrupt()可知

一般都是中断当前线程,其他线程需要检查访问允许权。

2.1 线程必须是活的

Interrupting a thread that is not alive need not have any effect.:中断的线程必须是isAlive()为true的也就是正常start()后到终结之间的线程。

2.2 一般的情况都会设置中断状态(即isInterrupt()返回true)

If none of the previous conditions hold then this thread's interrupt status will be set.:除了提到的几种条件,该方法只会设置线程的中断状态。至于哪几种条件,下面介绍。

2.3 清除中断状态(返回false)并接收一个异常

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.:第一种条件,也就是因为里面提到的这些方法而处于阻塞状态的情况ÿ

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值