interrupt方法的作用:
1、设置标志位为true
2、如果该线程正在阻塞中(比如在执行sleep)
此时就会把阻塞状态唤醒
通过抛出异常方式让sleep立即结束
注意:
当sleep被唤醒的时候,sleep会自动把isinterrupted标志位清空(true->false)
这就导致下次循环,循环仍然可以继续执行
public class Demo6 {
public static void main(String[] args) {
Thread t = new Thread(() -> {
// currentThread 是获取到当前线程实例.
// 此处 currentThread 得到的对象就是 t
// isInterrupted 就是 t 对象里自带的一个标志位.
while (!Thread.currentThread().isInterrupted()) {
System.out.println("hello t");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// e.printStackTrace();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
});
t.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 把 t 内部的标志位给设置成 true
t.interrupt();
}
}