线程中断相关方法介绍及区别
1、interrupt
interrupt方法用于中断线程。调用该方法的线程的状态为将被置为"中断"状态。注意:线程中断仅仅是置线程的中断状态位,不会停止线程。需要用户自己去监视线程的状态为并做处理。支持线程中断的方法(也就是线程中断后会抛出interruptedException的方法)就是在监视线程的中断状态,一旦线程的中断状态被置为“中断状态”,就会抛出中断异常,并且会清理掉线程的中断状态,抛出异常说明当前线程阻塞的代码已经被中断,不需要继续保持中断状态了。
2、isInterrupted
返回线程中断状态,代表线程是否被中断过,不会清理中断状态
3、interrupted
这是一个静态方法,作用于当前线程,返回当前线程是否被中断过,并且清理中断状态
实例:
public static void main(String[] args) throws Exception{
Thread t = new Thread(new Runnable() {
public void run() {
while (true){
try {
Thread.sleep(1000);
System.out.println("running");
}catch (InterruptedException e){
System.out.println("收到中断 但是不响应");
}
}
}
});
t.start();
Thread.sleep(3000);
// 如果线程不响应中断 无法中断线程
t.interrupt();
// jvm不建议使用的方法 会让线程之间介绍,线程状态未知的情况下 将线程结束
// t.stop();
}
常见check的代码
if(Thread.interrupted()){ // 会清理掉中断状态
// do something
}