无法在 Java 中停止线程

Can't stop thread in Java

我正在尝试创建一个线程然后中断它。但它不会停止并导致异常。谁能解释我做错了什么?谢谢

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();
                }
            }
        }
    }
}

根据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.

由于您使线程休眠 1000 毫秒,因此当您调用 test.interrupt() 时,线程几乎一直处于休眠状态。所以 InterruptedException 会被抛出。因此,您应该在 catch 子句处退出循环。

当您捕获 InterruptedException 退出 while 循环时包含一个 break

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

internal flag 在调用 interrupt 后重置。 您必须在捕获 thread 时再次调用它。 the Java Specialists Newsletter

中也涵盖了该主题

In my example, after I caught the InterruptedException, I used Thread.currentThread().interrupt() to immediately interrupted the thread again. 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

像这样的东西应该可以工作:

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

这可以确保执行其余代码。