interrupt()方法的简单理解

interrupt() 方法只是改变中断状态而已,它不会中断一个正在运行的线程。
这一方法实际完成的是,给受阻塞的线程发出一个中断信号,这样受阻线程就得以退出阻塞的状态。
更确切的说,如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,此时调用该线程的interrupt()方法,那么该线程将抛出一个 InterruptedException中断异常(该线程必须事先预备好处理此异常),从而提早地终结被阻塞状态。如果线程没有被阻塞,这时调用 interrupt()将不起作用,直到执行到wait(),sleep(),join()时,才马上会抛出 InterruptedException。

示例代码如下:

复制代码
public class InterruptTest {

    public static void main(String[] args) {
        for(int i=0;i<5;i++){
                Thread thread=new Thread( new InterruptThread());
                thread.start();
                thread.interrupt();
        }
    }

     static  class   InterruptThread implements  Runnable  {
         @Override
         public void run() {
             try {
                 Thread.sleep(2000);
             } catch (InterruptedException e) {
                 System.out.println("线程处于阻塞状态时,中断线程,就会抛出异常。");
                 e.printStackTrace();
             }

         }
     }
}
复制代码

 

运行的其中一种结果:

线程处于阻塞状态时,中断线程,就会抛出异常。
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at com.thread.InterruptTest$InterruptThread.run(InterruptTest.java:17)
    at java.lang.Thread.run(Thread.java:748)

 

参考博客:https://blog.csdn.net/zhangliangzi/article/details/52485319

posted on   乐之者v  阅读(8186)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示