最近弄一个自定义的线程池,发现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.:第一种条件,也就是因为里面提到的这些方法而处于阻塞状态的情况,