简体   繁体   English

这是正确“停止”线程的正确方法吗?

[英]is this the correct way to 'stop' a thread gracefully?

instead of continuous checking of variable inside a loop: 而不是连续检查循环内的变量:

class Tester {
    public static void main() {
        Try t = new Try();
        Thread.sleep(10); //wait for 10 milliseconds
        t.interrupt(); // 'interrupt' i.e stop the thread
    }
}

public class Try extends Thread {
    public void interrupt() {
        //perform all cleanup code here
        this.stop();
        /*stop() is unsafe .but if we peform all cleanup code above it should be okay ???. since thread is calling stop itself?? */
    }
}

In order to perform interrupt in a good manner you should poll for the "interrupted()" method inside the thread that is being interrupted. 为了以良好的方式执行中断,您应该轮询正在被中断的线程内的“interrupted()”方法。 Just be aware that calling interrupted() method resets the interruption flag (that is set when calling interrupt()). 请注意,调用interrupted()方法会重置中断标志(在调用interrupt()时设置)。

I guess the bottom line is that you have to continuously poll inside the thread in order to perform a graceful interruption. 我想底线是你必须在线程内连续轮询才能执行优雅的中断。

You should never ever call .stop() on a Thread, period. 你永远不应该在一个Thread,句点上调用.stop()。 It's not enough for the thread to perform its own cleanup. 线程执行自己的清理是不够的。 Since calling .stop() immediately releases all monitors, other threads may see shared data in an inconsistent state which may result in almost impossible to track errors. 由于调用.stop()会立即释放所有监视器,因此其他线程可能会看到处于不一致状态的共享数据,这可能导致几乎无法跟踪错误。

Use Thread.interrupt() method instead of Thread.stop(). 使用Thread.interrupt()方法而不是Thread.stop()。 In the interrupted thread you can catch the InterruptedException and do any cleanup required. 在中断的线程中,您可以捕获InterruptedException并执行所需的任何清理。

A similar questions has already been asked here , you can find a code sample there too. 这里已经提出类似的问题,您也可以在那里找到代码示例。

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

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