- 浏览: 142313 次
- 性别:
- 来自: 北京
最新评论
-
66jacky:
请问,如果要把某些信息写tag或者修改tag怎么做?
利用《Java MP3 ID3 Tag Library》读取mp3文件ID3信息 -
snowtree_ok:
老大,id3v2还是乱码哦。id3v1你是怎么改的呢?能帮忙发 ...
利用《Java MP3 ID3 Tag Library》读取mp3文件ID3信息 -
yuyuyc:
利用《Java MP3 ID3 Tag Library》读取mp3文件ID3信息 -
qianxueyiran:
老大,能把修改后的jid3lib的源码发给我一份吗,我用你的j ...
利用《Java MP3 ID3 Tag Library》读取mp3文件ID3信息 -
airpeng:
import java.io.File;
import jav ...
利用《Java MP3 ID3 Tag Library》读取mp3文件ID3信息
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.
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 the catch
or finally
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.
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:
static void sneakyThrow(Throwable t) {
Thread.currentThread().stop(t);
}
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 JavaSoft's 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:
private Thread blinker;
public void start() {
blinker = new Thread(this);
blinker.start();
}
public void stop() {
blinker.stop(); // UNSAFE!
}
public void run() {
Thread thisThread = Thread.currentThread();
while (true) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
You can avoid the use of Thread.stop
by replacing the applet's stop
and run
methods with:
private volatile Thread blinker;
public void stop() {
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
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:
public void stop() {
Thread moribund = waiter;
waiter = null;
moribund.interrupt();
}
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.
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.
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.
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
:
private boolean threadSuspended;
Public void mousePressed(MouseEvent e) {
e.consume();
if (threadSuspended)
blinker.resume();
else
blinker.suspend(); // DEADLOCK-PRONE!
threadSuspended = !threadSuspended;
}
You can avoid the use of Thread.suspend
and Thread.resume
by replacing the event handler above with:
public synchronized void mousePressed(MouseEvent e) {
e.consume();
threadSuspended = !threadSuspended;
if (!threadSuspended)
notify();
}
and adding the following code to the "run loop":
synchronized(this) {
while (threadSuspended)
wait();
}
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:
public void run() {
while (true) {
try {
Thread.currentThread().sleep(interval);
synchronized(this) {
while (threadSuspended)
wait();
}
} catch (InterruptedException e){
}
repaint();
}
}
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:
if (threadSuspended) {
synchronized(this) {
while (threadSuspended)
wait();
}
}
In the absence of explicit synchronization, threadSuspended must be made volatile to ensure prompt communication of the suspend-request.
The resulting run
method is:
private boolean volatile threadSuspended;
public void run() {
while (true) {
try {
Thread.currentThread().sleep(interval);
if (threadSuspended) {
synchronized(this) {
while (threadSuspended)
wait();
}
}
} catch (InterruptedException e){
}
repaint();
}
}
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:
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
thisThread.sleep(interval);
synchronized(this) {
while (threadSuspended && blinker==thisThread)
wait();
}
} catch (InterruptedException e){
}
repaint();
}
}
public synchronized void stop() {
blinker = null;
notify();
}
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.
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.
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!
Thread.stop
deprecated?
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.ThreadDeath
exception and fix the damaged object?
ThreadDeath
exception almost anywhere. All synchronized methods and blocks would have to be studied in great detail, with this in mind.
ThreadDeath
exception while cleaning up from the first (in the catch
or finally
clause). Cleanup would have to repeated till it succeeded. The code to ensure this would be quite complex.
Thread.stop(Throwable)
?
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:Thread.stop
?
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 JavaSoft's 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).start
, stop
and run
methods: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:Thread.interrupt
?
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.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.Thread.suspend
and Thread.resume
?
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
.blinker
:Thread.destroy
?
Runtime.runFinalizersOnExit
deprecated?
发表评论
-
利用《Java MP3 ID3 Tag Library》读取mp3文件ID3信息
2010-03-16 11:42 10850《Java MP3 ID3 Tag Librar ... -
[转]用Sql添加删除字段,判断字段是否存在的方法
2010-03-13 14:56 4531增加字段 alter ... -
使用SourceForge.net作为公共CVS/SVN服务器
2010-02-10 12:00 5784为了能够在工作地点和家里或任意地方同步更新到自己的项目代 ... -
getOutputStream()和getWriter()不能同时用
2009-12-01 12:44 2885getOutputStream 和 getWriter方法不能 ... -
【转载】如何在下载文件名中使用UTF-8编码
2009-10-27 19:47 1288版权声明:可以任意转 ... -
【转】Servlet 准确的输出文件格式
2009-10-20 12:34 1636首先从获得 servlet 的输 ... -
【转】出现java.lang.NoClassDefFoundError的错误的一种原因和解决办法
2009-10-17 19:45 1488今天在跑某java程序时,遇到了java.lang.NoCla ... -
comparator对list排序
2009-08-09 18:04 2076Collections.sort() 对 List 排序 im ... -
一定要记得关session!
2009-07-26 09:41 923今天早上再次查看了tomcat的日志,只有4K多,而前 ... -
java.net.SocketException: Broken pipe报错可能的原因
2009-07-24 12:53 5803作者: 2hei 发表于2008年12 ... -
使用Maven管理Eclipse Java项目
2009-07-13 11:06 1457本文可以任意转载,但请保留原出处: http://www.we ... -
“胡萝卜的梦”----SRM 401 DIV 2 250points 题目和自己的答案(非权威)
2008-05-23 23:46 959Problem Statement John wor ...
相关推荐
自.NET 2.0以来,Thread.Suspend()与Thread.Resume()方法已过时,VS提示可以使用如Monitor等技术,但是对于刚接触同步控制的人来说理解起来太复杂。本人利用Thread.Abort()与Thread.Interrupt()可以引起目标线程异常...
在设备初始化时,例如`mxc_board_init`,会将设备注册到电源管理列表`dpm_list`,在后续的`dpm_suspend`和`dpm_resume`过程中,系统会遍历此列表执行相应的操作。 此外,Android内核提供了接口函数,如`wake_lock_...
- 当设备进入 Suspend 状态时,LCD 可能会被关闭以节约电力。 - 在 Resume 时,LCD 需要重新初始化并恢复到之前的状态。 #### TP (Touch Panel) - **定义**:触摸屏面板,用户与设备交互的主要接口。 - **控制**...
hal库 FreeRTOS-Task-suspend&resume
在这个例子中,main线程不断地suspend和resume子线程,而子线程不断地执行printf语句。由于printf函数内部使用了Critical Section,而子线程在执行printf时可能会hold这个Critical Section。如果main线程在这个时候...
当定义了一个AFTER SUSPEND触发器,它会在一个事务被挂起后执行,这可能用于记录事务状态、更新审计日志或者执行其他与事务管理相关的操作。 描述中提到的博文链接虽然没有提供具体内容,但我们可以推断这篇博文...
ThreadGroup 还提供了一些其他的方法,例如 stop() 方法可以停止当前 ThreadGroup 中的所有线程,resume() 方法可以恢复当前 ThreadGroup 中的所有线程,suspend() 方法可以暂停当前 ThreadGroup 中的所有线程等。...
1. **任务管理**:RTT的任务(Task)是系统执行的基本单元,开发者可以通过`rt_thread_create`创建任务,`rt_thread_startup`启动任务,`rt_thread_delete`删除任务,以及`rt_thread_suspend`和`rt_thread_resume`...
描述中的内容与标题相同,进一步确认了这是一个名为"ACER_SUSPEND & REBOOT V1.1"的软件版本,版本号为1.1,可能包含了一些改进和修复了上一版本的问题。 标签"ACER_SUSPEND&R"简化了标题中的关键词,强调了该软件...
休眠/唤醒在嵌入式Linux中是非常重要的部分,嵌入式设备尽可能的进入休眠状 态来延长电池的续航时间.这篇文章就详细介绍一下Linux中休眠/唤醒是如何工作 的, 还有Android中如何把这部分和Linux的机制联系起来的.
- 该函数位于`kernel/power/earlysuspend.c`中,用于调度早期挂起(`early_suspend`)和晚期恢复(`late_resume`)的工作。 - **代码示例**: ```c request_suspend_state() { queue_work(suspend_work_queue, &...
* tx_thread_resume():恢复线程的执行 * tx_thread_sleep():使线程进入睡眠状态 * tx_thread_suspend():暂停线程的执行 * tx_thread_terminate():终止线程的执行 * tx_thread_wait_abort():等待线程的终止 ...
RT-Thread 是一款主要由中国开源社区主导开发的开源实时操作系统。实时线程操作系统不仅仅是一个单一的实时操作系统内核,它也是一个完整的应用系统,包含了实时、嵌入式系统相关的各个组件:TCP/IP协议栈,文件系统...
在Java中,可以使用`Thread.suspend()`方法来挂起线程,但需要注意,这个方法会使得线程陷入阻塞状态,直到被其他线程唤醒。然而,`Thread.suspend()`和相应的`Thread.resume()`方法已不推荐使用,因为它们可能导致...
- `suspend()` 和 `resume()`:挂起和恢复线程,由于可能导致死锁,这两个方法也被废弃。 二、线程的优先级 1. 线程调度策略 Java中的线程调度有两种策略:抢占式调度和合作式调度。Java采用抢占式调度,优先级...
在RT-Thread中,线程可以理解为任务或子程序,它们并发执行,共享进程的内存空间。线程管理主要包括线程创建、销毁、挂起、恢复、优先级设置等操作。 #### 1. 线程创建 在RT-Thread中,开发者可以通过`rt_thread_...
标题 "i915_suspend.rar_V2" 暗示了这是一个关于英特尔i915图形控制器在Linux系统中挂起(suspend)功能的更新版本,可能是针对内核2.13.6的一个补丁或驱动程序。在这个压缩包里包含的文件 "i915_suspend.c" 是C语言...
使用stop方法强行终止,但是不推荐这个方法,因为stop和suspend及resume一样都是过期废弃的方法;使用interrupt方法中断线程。 三、notify和notifyAll的区别 notify和notifyAll都是用于线程间的通信的方法,但是...
// thread.resume(); // 恢复线程(与suspend配合使用) // thread.stop(); // 停止线程(不推荐,因为不安全) // thread.interrupt(); // 中断线程,通常用于通知线程退出循环 } } ``` 在用户级线程调度中,...