【问题标题】:Can't stop thread in Java无法停止Java中的线程
【发布时间】:2015-09-10 10:43:30
【问题描述】:

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

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

【问题讨论】:

  • 导致异常。什么例外?
  • 好像work fine
  • @BoristheSpider 也许当你执行它时,执行中断时线程正在运行。你跑了几次?

标签: java multithreading interrupt interrupted-exception


【解决方案1】:

根据javadocs

线程中断被忽略,因为线程在 中断的时间将通过此方法返回来反映 假的。

由于你让线程休眠了 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;
            }
        }

【讨论】:

    【解决方案2】:

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

    也涵盖了该主题

    在我的示例中,在捕获 InterruptedException 后,我使用了 Thread.currentThread().interrupt() 来立即中断 再次线程。为什么这是必要的?当异常被抛出时, 中断标志被清除,所以如果你有嵌套循环,你会 在外部循环中造成麻烦

    这样的事情应该可以工作:

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

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

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 2013-05-02
      • 1970-01-01
      • 2014-07-10
      • 2013-04-18
      • 2013-04-19
      • 2016-11-27
      • 1970-01-01
      • 2018-11-03
      相关资源
      最近更新 更多