gpt4 book ai didi

java - 替代 Java 8 中的 Thread.stop()?

转载 作者:IT老高 更新时间:2023-10-28 21:02:01 24 4
gpt4 key购买 nike

现在 Thread.stop 已被删除,有什么办法可以强制 ThreadJava 8 下停止?这包括强制在 lock/synchronized/sleep/wait/infinite 循环上等待的线程停止。

这是作为 watchdog 的一部分用于应用程序,它可以检测它是否有死锁/卡住,强制终止线程,然后保存当前状态以避免丢失信息 - 虽然由于强制线程停止而导致此信息损坏的可能性很高,但最好拥有可能不正确的信息的副本而不是丢失它。

在不停止锁定线程的情况下尝试保存此信息是不可能的,因为保存它需要获取锁。

最佳答案

阅读这些文章,他们会解释:

  1. “为什么不推荐使用 Thread.stop、Thread.suspend、Thread.resume 和 Runtime.runFinalizersOnExit?” http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

  2. Joshua Bloch:“Effective Java (2nd Edition)”,第 66 条:同步访问共享可变数据

Joshua Bloch 解释了如何停止线程并说:

Consider the task of stopping one thread from another. The libraries provide the Thread.stop method, but this method was deprecated long ago because it is inherently unsafe—its use can result in data corruption. Do not use Thread.stop. A recommended way to stop one thread from another is to have the first thread poll a boolean field that is initially false but can be set to true by the second thread to indicate that the first thread is to stop itself.

使用此技术时,您还应该处理 boolean 字段的同步。我不想从 Joshua Bloch 的书中复制太多内容,但您会在其中和上面​​提到的官方 Oracle Java 文档中找到所有内容。

关于java - 替代 Java 8 中的 Thread.stop()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23317332/

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