中断()没有按预期工作(中断是如何工作的?)

发布于 2024-12-14 07:03:24 字数 895 浏览 0 评论 0原文

我想中断一个线程,但调用 interrupt() 似乎不起作用。下面是示例代码:

public class BasicThreadrRunner {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Basic(), "thread1");
        t1.start();
        Thread t3 = new Thread(new Basic(), "thread3");
        Thread t4 = new Thread(new Basic(), "thread4");
        t3.start();
        t1.interrupt();
        t4.start();
    }
}
class Basic implements Runnable{
    public void run(){
        while(true) {
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.err.println("thread: " + Thread.currentThread().getName());
                //e.printStackTrace();
            }
        }
    }
}

但输出看起来线程 1 仍在运行。谁能解释一下这个以及 interrupt() 是如何工作的?谢谢!

I want to interrupt a thread, but invoking interrupt() doesn't seem to work. Below is the sample code:

public class BasicThreadrRunner {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Basic(), "thread1");
        t1.start();
        Thread t3 = new Thread(new Basic(), "thread3");
        Thread t4 = new Thread(new Basic(), "thread4");
        t3.start();
        t1.interrupt();
        t4.start();
    }
}
class Basic implements Runnable{
    public void run(){
        while(true) {
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.err.println("thread: " + Thread.currentThread().getName());
                //e.printStackTrace();
            }
        }
    }
}

but the output looks like thread 1 is still running. Can anyone explain this as well as how interrupt() works? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

紫﹏色ふ单纯 2024-12-21 07:03:24

线程仍在运行只是因为您捕获了 InterruptedException 并继续运行。 interrupt() 主要在 Thread 对象中设置一个标志,您可以使用 isInterrupted() 检查该标志。它还会导致某些方法(特别是 sleep()join Object.wait())通过抛出 <代码>中断异常。它还会导致某些 I/O 操作立即终止。如果您看到 catch 块的打印输出,那么您可以看到 interrupt() 正在工作。

The thread is still running simply because you catch InterruptedException and keep running. interrupt() primarily sets a flag in the Thread object, which you can check with isInterrupted(). It also causes some methods -- sleep(), join Object.wait(), in particular -- to return immediately by throwing an InterruptedException. It also causes some I/O operations to immediately terminate. If you're seeing the printouts from your catch block, then you can see that interrupt() is working.

秋意浓 2024-12-21 07:03:24

正如其他人所说,您捕获了中断,但不对其执行任何操作。您需要做的是使用逻辑传播中断,例如

while(!Thread.currentThread().isInterrupted()){
    try{
        // do stuff
    }catch(InterruptedException e){
        Thread.currentThread().interrupt(); // propagate interrupt
    }
}

使用循环逻辑,例如while(true)只是惰性编码。相反,轮询线程的中断标志以便通过中断确定终止。

As others have said, you catch the interrupt, but do nothing with it. What you need to do is propagate the interrupt using logic such as,

while(!Thread.currentThread().isInterrupted()){
    try{
        // do stuff
    }catch(InterruptedException e){
        Thread.currentThread().interrupt(); // propagate interrupt
    }
}

Using looping logic, such as while(true) is just lazy coding. Instead, poll the thread's interrupted flag in order to determine termination via interruption.

乱了心跳 2024-12-21 07:03:24

++1,除了其他答案。我认为对此的误解是,在 Thread.sleep(1000); 调用之后,try/catch 块似乎完成了其工作,即尝试休眠1000ms,捕获任何可能中断我的睡眠尝试的内容

实际上发生的情况是,try/catch 块在睡眠时仍然非常活跃,即尝试睡眠 1000 毫秒,捕获任何可能在睡眠期间中断的内容

因此,原因是为什么异常会立即(以及之后)被捕获,因为线程刚刚开始睡眠。

++1, in addition to other answers. I believe the misconception about this was that it seemed the try/catch block finished its job after the Thread.sleep(1000); call i.e. try to sleep for 1000ms, catch anything that might interrupt my sleep attempt.

What is happening actually is that the try/catch block is still very much active while sleeping i.e. try to sleep for 1000ms, catch anything that might interrupt during my sleep

Hence the reason why the exception is being caught immediately (and afterwards) since the thread barely just started its sleep.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文