【问题标题】:Java Thread interruption: interrupt() vs stop()Java 线程中断:interrupt() 与 stop()
【发布时间】:2014-05-27 00:23:53
【问题描述】:

在 Java 中使用线程时遇到问题。在 Java 中中断线程时,interrupt() 和 stop() 之间首选的方法是什么?为什么?

感谢您的任何回复。

【问题讨论】:

  • 您阅读文档了吗?

标签: java multithreading methods interruption


【解决方案1】:

从理论上讲,按照您提出问题的方式,线程应该通过同步标志自行理解何时必须终止。

这是通过使用interrupt() 方法完成的,但您应该了解,只有当您的线程处于等待/睡眠状态(并且在这种情况下会引发异常)时,这才“有效”,否则您必须检查你自己,在你的线程的 run() 方法中,如果线程被中断(使用isInterrupted() 方法),并在你想要的时候退出。例如:

public class Test {
    public static void main(String args[]) {
        A a = new A(); //create thread object
        a.start(); //call the run() method in a new/separate thread)
        //do something/wait for the right moment to interrupt the thread
        a.interrupt(); //set a flag indicating you want to interrupt the thread

        //at this point the thread may or may not still running 

    }
}

class A extends Thread {

    @Override
    public void run() { //method executed in a separated thread
        while (!this.isInterrupted()) { //check if someone want to interrupt the thread
            //do something          
        } //at the end of every cycle, check the interrupted flag, if set exit
    }
}

【讨论】:

    【解决方案2】:

    Thread.stop() 在 java 8 中已被弃用,所以我想说Thread.interrupt() 是要走的路。 oracles site 有一个冗长的解释。它还提供了一个很好的例子来说明如何使用线程。

    【讨论】:

    • 该链接提供了许多在无限循环内干扰 InterruptedException 的示例。这是处理这些问题的正确方法,还是仅用于说明 Thread.stop() 并发症?
    • 我就是这样做的。基本上,您从某个顶层启动关闭并向下传播,中断并标记所有线程停止(从无限循环)并让它们以受控方式终止。
    • Thread.stop() 已被弃用十多年了。 Java 8 和更早版本的区别在于Thread.stop(Throwable) 现在抛出UnsupportedOperation。
    猜你喜欢
    • 2020-10-08
    • 2014-12-13
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    相关资源
    最近更新 更多