资讯动态

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

发布时间:2026/10/11 2:02:24 来源:尧图企业网站定制
之前我们使用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();}

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑