0
点赞
收藏
分享

微信扫一扫

JAVA 线程中的interrupt()函数

是波波呀 06-17 12:00 阅读 10

今天看到了interrupt()  来总结下


当线程在正常运行时,可以通过检查自身的中断标志位 (isInterrupted()) 来判断是否被请求中断。

interrupt() 的作用: interrupt() 方法并不会直接“杀死”或“暂停”一个线程。它只是向目标线程发送一个“中断请求”,并设置该线程内部的中断标志位为 true。如何响应这个请求,完全取决于线程本身的代码。

当线程处于阻塞状态(如 sleep(), join(), wait())时,如果被中断,会抛出 InterruptedException。

// 中断线程
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new MyThread();
        t.start();
        Thread.sleep(1000);
        t.interrupt(); // 中断t线程
        t.join(); // 等待t线程结束
        System.out.println("end");
    }
}

class MyThread extends Thread {
    public void run() {
        Thread hello = new HelloThread();
        hello.start(); // 启动hello线程
        try {
            hello.join(); // 等待hello线程结束
        } catch (InterruptedException e) {
            System.out.println("抛出 InterruptedException---MyThread线程");
            System.out.println("interrupted!");
        }
        hello.interrupt();
    }
}

class HelloThread extends Thread {
    public void run() {
        int n = 0;
        while (!isInterrupted()) {
            n++;
            System.out.println(n + " hello!");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("抛出 InterruptedException----hello线程");
                break;
            }
        }
    }
}

在这段代码中,MyThread线程在主线程睡眠10s之后被发送了interrupt中断请求,此时MyThread线程处于阻塞状态,它在等待HelloThread的结束,所以此处就会出发InterruptedException异常,并且,这个异常会清除线程的中断标志位。

然后,中断传递,执行 hello.interrupt()

执行结果

1 hello!

2 hello!

3 hello!

4 hello!

5 hello!

6 hello!

7 hello!

8 hello!

9 hello!

10 hello!

抛出 InterruptedException---MyThread线程

interrupted!

抛出 InterruptedException----hello线程

end

代码出处  廖雪峰的Java教程

中断线程 - Java教程 - 廖雪峰的官方网站


举报

相关推荐

0 条评论