简体   繁体   English

无法在 Java 中停止线程

[英]Can't stop thread in Java

I'm trying to create a thread and then interrupt it.我正在尝试创建一个线程,然后中断它。 But it doesn't stop and cause exception.但它不会停止并导致异常。 Can anybody explain what am I doing wrong?谁能解释一下我做错了什么? Thanks.谢谢。

public class Test {
    public static void main(String[] args) throws InterruptedException {
        //Add your code here - добавь код тут
        TestThread test = new TestThread();
        test.start();
        Thread.sleep(5000);
        test.interrupt();

    }

    public static class TestThread extends Thread {
        public void run() {
            while (!this.isInterrupted()) {
                try {
                    Thread.sleep(1000);
                    System.out.println("I did the Thread");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

According to javadocs :根据javadocs

A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.由于线程在中断时未处于活动状态而被忽略的线程中断将通过此方法返回 false 来反映。

Since you sleep the thread for 1000ms, when you call test.interrupt() , thread is asleep, almost all the times.由于您使线程休眠 1000 毫秒,因此当您调用test.interrupt() ,线程几乎一直处于休眠状态。 So InterruptedException will be thrown.所以会抛出InterruptedException Therefore you should exit the loop at the catch clause.因此,您应该在 catch 子句处退出循环。

Include a break when you catch InterruptedException to exit while loop.包括break时,你赶上InterruptedException到while循环退出。

 while (!this.isInterrupted()) {
            try {
                Thread.sleep(1000);
                System.out.println("I did the Thread");
            } catch (InterruptedException e) {
                break;
            }
        }

The internal flag gets resetted after calling interrupt .调用interruptinternal flag被重置。 You have to call it again in your catch of the thread .您必须在thread捕获中再次调用它。 The topic was also covered in the Java Specialists Newsletter Java 专家时事通讯中也涵盖了该主题

In my example, after I caught the InterruptedException, I used Thread.currentThread().interrupt() to immediately interrupted the thread again.在我的例子中,在我捕获到 InterruptedException 之后,我使用 Thread.currentThread().interrupt() 立即再次中断线程。 Why is this necessary?为什么这是必要的? When the exception is thrown, the interrupted flag is cleared, so if you have nested loops, you will cause trouble in the outer loops抛出异常时,中断标志被清除,所以如果你有嵌套循环,你会在外层循环中造成麻烦

Something like this should work:这样的事情应该工作:

   try {
            Thread.sleep(1000);
            System.out.println("I did the Thread");
        } catch (InterruptedException e) {
            this.interrupt();
           // No need for break
        }

This makes sure that the rest of the code is executed.这可确保执行其余代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM