java - Thread.stop() - 已弃用

标签 java multithreading

为什么在 Java 中不推荐使用 Thread.stop()?在他们的网站上,我看到以下内容:

Why is Thread.stop deprecated?

Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.

我不明白他们所说的“监视器”是什么意思。无论如何,我的问题是如果不应该调用 Thread.stop() 那么应该如何停止 Java 线程?

最佳答案

你问:

My question is if theres no way to stop a thread in Java then how to stop a thread?

答案:在 Java 中,没有干净、快速或可靠的方法来停止线程。

Thread termination is not so straight forward. A running thread, often called by many writers as a light-weight process, has its own stack and is the master of its own destiny (well daemons are). It may own files and sockets. It may hold locks. Abrupt Termination is not always easy: Unpredictable consequences may arise if the thread is in the middle of writing to a file and is killed before it can finish writing. Or what about the monitor locks held by the thread when it is shot in the head?

相反,线程依赖于一种称为中断合作机制。这意味着线程只能通知其他线程停止,而不是强制它们停止。

To stop threads in Java, we rely on a co-operative mechanism called Interruption. The concept is very simple. To stop a thread, all we can do is deliver it a signal, aka interrupt it, requesting that the thread stops itself at the next available opportunity. That’s all. There is no telling what the receiver thread might do with the signal: it may not even bother to check the signal; or even worse ignore it.

来源:https://codeahoy.com/java/How-To-Stop-Threads-Safely/

关于java - Thread.stop() - 已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16504140/

相关文章:

java - 将 Spring Boot 部署到 weblogic 12

java - java转换中导入org.json不存在错误

java - 是否可以读取可能同时写入的变量?

c# - 我怎样才能做一个有 5 秒暂停的无限循环

java - 将 for 循环转换为多线程 block

java - Disruptor如何使用他的环形缓冲区来读取文件?

java - HTML 音频标签在 apache tomcat 的 localhost 中不起作用

c++ - itk 3.20.1 处理器亲和性

java - java中通过字符串连接生成查询——变量值不被替换

c# - Thread.Sleep() 用于防止服务器过载