为什么Thread.stop()方法不安全使用? [英] Why Thread.stop() method isn't safe to use?

查看:899
本文介绍了为什么Thread.stop()方法不安全使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有效的Java书籍的引语:


提供Thread.stop方法,但是这个方法是
很久以前就被弃用,因为它本质上是不安全的 - 它的使用可能导致
在数据损坏。不要使用Thread.stop

任何人都可以告诉我为什么

推荐答案

如果你停止的线程持有临界锁怎么办?如果线程将一个对象放在不一致的状态,并没有机会还原它呢?停止线程的正确方法是与它的合作,而不是强制它从外面停止。

What if the thread you stop holds a critical lock? What if the thread has placed an object into an inconsistent state and hasn't had a chance to restore it yet? The correct way to stop a thread is with its cooperation, not by forcing it to stop from the outside.

此外,它根本没有逻辑意义。应用程序中的所有线程都应该合作以实现相同的目的。如果有东西不应该做,没有线程应该做。应该没有理由停止线程 - 它应该只是编码做某事,如果这是应用程序整体需要做的第一位。如果一个线程需要被停止,它只是因为它运行的代码坏了 - 做事情,即使他们不应该做。只需修复该代码。

Also, it simply doesn't make logical sense. All the threads in an application are supposed to be cooperating to achieve the same ends. If there's something that shouldn't be done, no thread should do it. There should be no reason to stop a thread -- it should only be coded to do something if that is something the application as whole needs done in the first place. If a thread needs to be stopped, it's only because the code it is running is broken -- doing things even if they should not be done. Just fix that code.

这篇关于为什么Thread.stop()方法不安全使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆