JavaSE学习——线程的睡眠和中断
之前我们使用sleep方法来设置线程睡眠的时间,其实它还有一个作用,就是响应中断,比如代码正处于睡眠中,那么这时候中断标志是true会使得sleep方法立刻抛出 InterruptedException!并且:中断标记会被自动清除。这就是一种响应。
比如下面的代码。t.interrupt()把线程的中断标志位改成 true。.isInterrupted())检查是否被中断,如果被中断,就响应break的内容。
public class Main{ public static void main(String[] args) throws InterruptedException { Thread t = new Thread(()->{ System.out.println("线程开始运行"); while (true){if(Thread.currentThread().isInterrupted()){ break; }} System.out.println("线程被中断了"); }); t.start(); try{ Thread.sleep(3000);t.interrupt();} catch (InterruptedException e) { throw new RuntimeException(e); } } }当然,这个t.interrupt()中断信号是柔性的,只是发出一个标志,至于是否立刻中断/不响应都可以,不强制执行。
就像上面的示例代码,可以选择复位中断标记
if(Thread.currentThread().isInterrupted()){
Thread.interrupted();
}
