gpt4 book ai didi

java - Thread.stop() - 已弃用

转载 作者:IT老高 更新时间:2023-10-28 20:41:29 26 4
gpt4 key购买 nike

为什么在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com