Java 中断线程(interrupt)
@author:Jingdai
@date:2020.10.06
概念
当
A
线程想让B
线程终止运行,应该怎么办呢?在Java之前的版本中,可以利用stop
方法来使一个线程终止,但是该方法已经被废弃了,不要这么用。现在可以在
A
线程中调用B
线程的interrupt()
方法,来使B
线程知道有线程想要使自己终止,但是是否终止取决于B
线程自己,B
完全可以不理会这个终止请求。(当然最好不要这么做)下面我们来看看细节。
相关函数介绍
void interrupt()
中断这个线程。
boolean isInterrupted()
检查这个线程是否被中断。
static boolean interrupted()
检查当前线程是否被中断,该方法在调用后还会清除该线程的中断状态。
示例解释
boolean isInterrupted()
方法和static boolean interrupted()
方法区别如下代码首先测试
boolean isInterrupted()
方法。public static void main(String[] args) { Thread.currentThread().interrupt(); System.out.println(Thread.currentThread().isInterrupted()); // true System.out.println(Thread.currentThread().isInterrupted()); // true }
会发现两次输出都是
true
。接着测试
static boolean interrupted()
方法。public static void main(String[] args) { Thread.currentThread().interrupt(); System.out.println(Thread.interrupted()); // true System.out.println(Thread.interrupted()); // fa