interrupt()方法用于将调用方法的线程设置一个中断标记位,并不一定真正的停止线程
isInterrupted()方法用于判断线程的中断标记位,不会重置标记位
因为等待状态 和 阻塞状态会一直监听线程状态。当监视到线程中断标记位后,会立即抛出异常。
public class MainTest {
static Object object = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
//情况1. 用于打断睡眠中的线程 打断标记设置为假
try {
log.debug("sleep");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//情况2: 用于打断阻塞中的线程 打断标记设置为假
// synchronized (object){
// try {
// object.wait();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
},"t1");
t1.start();
Thread.sleep(1000);
log.debug("interrupt");
t1.interrupt();
System.out.println("打断标记:"+t1.isInterrupted());
}
}