java中的线程(1):如何正确停止线程Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?
转自 : http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
1.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.
2.Couldn't I just catch the ThreadDeath
exception and fix the damaged object?
In theory, perhaps, but it would vastly complicate the task of writing correct multithreaded code. The task would be nearly insurmountable for two reasons:
- A thread can throw a
ThreadDeath
exception almost anywhere. All synchronized methods and blocks would have to be studied in great detail, with this in mind. - A thread can throw a second
ThreadDeath
exception while cleaning up from the first (in thecatch
orfinally
clause). Cleanup would have to repeated till it succeeded. The code to ensure this would be quite complex.
In sum, it just isn't practical.
3.What about Thread.stop(Throwable)
?
In addition to all of the problems noted above, this method may be used to generate exceptions that its target thread is unprepared to handle (including checked exceptions that the thread could not possibly throw, were it not for this method). For example, the following method is behaviorally identical to Java's throw
operation, but circumvents the compiler's attempts to guarantee that the calling method has declared all of the checked exceptions that it may throw:
1 static void sneakyThrow(Throwable t) { 2 Thread.currentThread().stop(t); 3 }
4.What should I use instead of Thread.stop
?
Most uses of stop
should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. (This is the approach that the Java Tutorial has always recommended.) To ensure prompt communication of the stop-request, the variable must be volatile (or access to the variable must be synchronized).
For example, suppose your applet contains the following start
, stop
and run
methods:
1 private Thread blinker; 2 3 public void start() { 4 blinker = new Thread(this); 5 blinker.start(); 6 } 7 8 public void stop() { 9 blinker.stop(); // UNSAFE! 10 } 11 12 public void run() { 13 Thread thisThread = Thread.currentThread(); 14 while (true) { 15 try { 16 thisThread.sleep(interval); 17 } catch (InterruptedException e){ 18 } 19 repaint(); 20 } 21 }
You can avoid the use of Thread.stop
by replacing the applet's stop
and run
methods with:
1 private volatile Thread blinker; 2 3 public void stop() { 4 blinker = null; 5 } 6 7 public void run() { 8 Thread thisThread = Thread.currentThread(); 9 while (blinker == thisThread) { 10 try { 11 thisThread.sleep(interval); 12 } catch (InterruptedException e){ 13 } 14 repaint(); 15 } 16 }
5.How do I stop a thread that waits for long periods (e.g., for input)?
That's what the Thread.interrupt
method is for. The same "state based" signaling mechanism shown above can be used, but the state change (blinker = null
, in the previous example) can be followed by a call to Thread.interrupt
, to interrupt the wait:
1 public void stop() { 2 Thread moribund = waiter; 3 waiter = null; 4 moribund.interrupt(); 5 }
For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException
is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation:
Thread.currentThread().interrupt();
This ensures that the Thread will reraise the InterruptedException
as soon as it is able.
6.What if a thread doesn't respond to Thread.interrupt
?
In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt
, it wouldn't respond to Thread.stop
either. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.
7.Why are Thread.suspend
and Thread.resume
deprecated?
Thread.suspend
is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume
, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes.
8.What should I use instead of Thread.suspend
and Thread.resume
?
As with Thread.stop
, the prudent approach is to have the "target thread" poll a variable indicating the desired state of the thread (active or suspended). When the desired state is suspended, the thread waits using Object.wait
. When the thread is resumed, the target thread is notified using Object.notify
.
For example, suppose your applet contains the following mousePressed event handler, which toggles the state of a thread called blinker
:
1 private boolean threadSuspended; 2 3 Public void mousePressed(MouseEvent e) { 4 e.consume(); 5 6 if (threadSuspended) 7 blinker.resume(); 8 else 9 blinker.suspend(); // DEADLOCK-PRONE! 10 11 threadSuspended = !threadSuspended; 12 }
You can avoid the use of Thread.suspend
and Thread.resume
by replacing the event handler above with:
1 public synchronized void mousePressed(MouseEvent e) { 2 e.consume(); 3 4 threadSuspended = !threadSuspended; 5 6 if (!threadSuspended) 7 notify(); 8 }
and adding the following code to the "run loop":
1 synchronized(this) { 2 while (threadSuspended) 3 wait(); 4 }
The wait
method throws the InterruptedException
, so it must be inside a try ... catch
clause. It's fine to put it in the same clause as the sleep
. The check should follow (rather than precede) the sleep
so the window is immediately repainted when the the thread is "resumed." The resulting run
method follows:
1 public void run() { 2 while (true) { 3 try { 4 Thread.currentThread().sleep(interval); 5 6 synchronized(this) { 7 while (threadSuspended) 8 wait(); 9 } 10 } catch (InterruptedException e){ 11 } 12 repaint(); 13 } 14 }
Note that the notify
in the mousePressed
method and the wait
in the run
method are inside synchronized
blocks. This is required by the language, and ensures that wait
and notify
are properly serialized. In practical terms, this eliminates race conditions that could cause the "suspended" thread to miss a notify
and remain suspended indefinitely.
While the cost of synchronization in Java is decreasing as the platform matures, it will never be free. A simple trick can be used to remove the synchronization that we've added to each iteration of the "run loop." The synchronized block that was added is replaced by a slightly more complex piece of code that enters a synchronized block only if the thread has actually been suspended:
1 if (threadSuspended) { 2 synchronized(this) { 3 while (threadSuspended) 4 wait(); 5 } 6 }
In the absence of explicit synchronization, threadSuspended must be made volatile to ensure prompt communication of the suspend-request.
The resulting run
method is:
1 private boolean volatile threadSuspended; 2 3 public void run() { 4 while (true) { 5 try { 6 Thread.currentThread().sleep(interval); 7 8 if (threadSuspended) { 9 synchronized(this) { 10 while (threadSuspended) 11 wait(); 12 } 13 } 14 } catch (InterruptedException e){ 15 } 16 repaint(); 17 } 18 }
9.Can I combine the two techniques to produce a thread that may be safely "stopped" or "suspended"?
Yes; it's reasonably straightforward. The one subtlety is that the target thread may already be suspended at the time that another thread tries to stop it. If the stop method merely sets the state variable (blinker) to null, the target thread will remain suspended (waiting on the monitor), rather than exiting gracefully as it should. If the applet is restarted, multiple threads could end up waiting on the monitor at the same time, resulting in erratic behavior.
To rectify this situation, the stop method must ensure that the target thread resumes immediately if it is suspended. Once the target thread resumes, it must recognize immediately that it has been stopped, and exit gracefully. Here's how the resulting run and stop methods look:
1 public void run() { 2 Thread thisThread = Thread.currentThread(); 3 while (blinker == thisThread) { 4 try { 5 thisThread.sleep(interval); 6 7 synchronized(this) { 8 while (threadSuspended && blinker==thisThread) 9 wait(); 10 } 11 } catch (InterruptedException e){ 12 } 13 repaint(); 14 } 15 } 16 17 public synchronized void stop() { 18 blinker = null; 19 notify(); 20 }
If the stop method calls Thread.interrupt, as described above, it needn't call notify as well, but it still must be synchronized. This ensures that the target thread won't miss an interrupt due to a race condition.
10.What about Thread.destroy
?
Thread.destroy
has never been implemented. If it were implemented, it would be deadlock-prone in the manner of Thread.suspend
. (In fact, it is roughly equivalent to Thread.suspend
without the possibility of a subsequent Thread.resume
.) We are not implementing it at this time, but neither are we deprecating it (forestalling its implementation in future). While it would certainly be deadlock prone, it has been argued that there may be circumstances where a program is willing to risk a deadlock rather than exit outright.
11.Why is Runtime.runFinalizersOnExit
deprecated?
Because it is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock. While this problem could be prevented if the class whose objects are being finalized were coded to "defend against" this call, most programmers do not defend against it. They assume that an object is dead at the time that its finalizer is called.
Further, the call is not "thread-safe" in the sense that it sets a VM-global flag. This forces every class with a finalizer to defend against the finalization of live objects!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
2016-10-04 java 反射工具类
2015-10-04 屏幕尺寸,屏幕分辨率,屏幕密度,各种长宽单位(px,sp,dp,in.pt,mm)
2015-10-04 多设备官方教程(7)如何支持多种语言
2015-10-04 多设备官方教程(6)控制多版本API
2015-10-04 多设备官方教程(5)多屏幕(下)用代码控制运行时各布局应何时显示
2015-10-04 多设备官方教程(4)多屏幕(中)各大小屏幕都有个布局文件,再对它们生成相同的别名,.9图片技术
2015-10-04 多设备官方教程(3)多屏幕(上)用密度不用像素