JavaSE学习——线程的睡眠和中断

张开发
2026/4/18 7:29:30 15 分钟阅读

分享文章

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();}

更多文章