java多线程情况下调用 interrupt 方法时的一些细节
1. 设置标志位 isIntertupted 时尝试唤醒堵塞状态线程的情况.
public class Demo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
// currentThread 获取当前线程的实例
// Thread.currentThread() <=> thread
// isInterrupted() 就是一个 thread 的一个标志位
// isInterrupted() 默认为 false
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Hello thread");
try {
// 在执行interrupt 时 sleep 会被立即唤醒并将标志位改为false
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// 将 isInterrupted 标志位设置为 true
thread.interrupt();
}
}
- 按照我们的愿意一下是我们想要的结果
- 但是实际上的运行结果
- 原因
- 如果需要让程序结束那么就应该在catch 里面添加一个break
public class Demo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
// currentThread 获取当前线程的实例
// Thread.currentThread() <=> thread
// isInterrupted() 就是一个 thread 的一个标志位
// isInterrupted() 默认为 false
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Hello thread");
try {
// 在执行interrupt 时 sleep 会被立即唤醒并将标志位改为false
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
// 如果需要结束循环就需要加上一个break
break;
}
}
});
thread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// 将 isInterrupted 标志位设置为 true
thread.interrupt();
}
}
- 结果
[总结] - sleep 在执行时会检查 isInterrupted 标志位是否为false 如果不是就会将其置位false
- interrupt 会将isInterrupted 标志位 设置为ture ,并将处于阻塞的状态下调用该方法的线程唤醒
小提示:
- 当执行到 interrupt 时恰好线程被自动唤醒时就会不抛异常结束程序