且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

停止/销毁线程

更新时间:2022-06-12 20:58:24

线程破坏停止方法固有的死锁倾向和不安全的。它们的存在也给了幻觉,有可能是立即停止另一个线程,当别的东西告诉它以某种方式。

The thread destroy and stop methods are inherently deadlock prone and not safe. Their existence also gives the illusion that there might be some way of halting another thread immediately when something else tells it to.

我理解你的想法,从您的角度来看他们是一个主线程,在该线程没有收到它的响应的工作线程在一段时间,你想杀死它,并重新启动它,不关心什么就看的。但之所以这些方法都去precated是你的的关心线程是最多。许多。

I understand your thinking, from your point of view their is one main thread, and when this thread hasn't received a response from it's worker thread in a while you'd like to kill it and restart it, without caring what it's up to. But the reason those methods are deprecated is you should care what the thread is up to. A lot.

如果该线程有大约以后需要使用一个变量的锁?如果一个线程的文件处理打开的是什么?在所有这些情况下,更多的人,简单地停止线程在它的当前操作会留下的东西乱七八糟 - 很可能你的应用程序只会进一步崩溃的路线

What if the thread has a lock around a variable you need to use later? What if a thread has a file handle open? In all these cases, and many more, simply stopping the thread at it's current operation would leave things in mess -- quite likely your application would just crash further down the line.

因此​​,为了使一个线程被中断或取消,能够或停止的,它必须管理这本身。如果一个线程或操作提供没办法为自己被打断,那么你就不能中断它 - 假定这样做是不安全的。

So in order for a thread to be interruptible or cancel-able or stoppable, it has to manage this itself. If a thread or operation provides no way for itself to be interrupted, then you cannot interrupt it - it is assumed to do so would be unsafe.

如果您可运行实际上就是

If you runnable is literally

public void run() {
   doSomething();
}

那么有没有办法打断它。人们希望,如果 DoSomething的是一个长期操作,有可能是一种方法来与它进行交互增量的东西,如

then there is no way to interrupt it. One would hope that if doSomething were a long operation that there might be a way to either interact with it incrementally with something like

public void run() {
   while (running) {
       MyParser.parseNext();
   }
}

或者能够通过参考其指示线程是否被中断或没有,并希望该方法将中断本身在合适的位置,以通过在变量中。

or to be able to pass in a variable by reference which indicates whether the thread is interrupted or not, and hopefully the method would interrupt itself at suitable location.

还记得阻止操作阻塞。有没有办法来解决这个问题,则无法取消它的一部分的方式,通过。

Remember a blocking operation is blocking. There is no way to get around that, you cannot cancel it part way through.