我刚从sun的文档中了解到,当我调用thread.stop()方法时,run()方法将在ThreadDeath错误被抛出时终止,并且还释放此线程持有的所有锁,如何证明它?
我尝试了我的测试程序,如下所示:
public static void main(String[] args) {
final Object lock = new Object();
try {
Thread t = new Thread() {
public synchronized void run() {
try {
synchronized (lock) {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++)
System.out.println("runing.." + i);
System.out
.println((System.currentTimeMillis() - start) / 1000);
}
} catch (Throwable ex) {
System.out.println("Caught in run: " + ex);
ex.printStackTrace();
}
}
};
t.start();
// Give t time to get going...
Thread.sleep(100);
t.stop(); // EXPECT COMPILER WARNING
} catch (Throwable t) {
System.out.println("Caught in main: " + t);
t.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
只有当我在run()方法中放入wait()时,我才能捕获ThreadDeath错误,有没有人知道jvm如何处理stop()的细节?
public static void main(String[] args) {
final Object lock = new Object();
try {
Thread t = new Thread() {
public synchronized void run() {
try {
synchronized (lock) {
wait();
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++)
System.out.println("runing.." + i);
System.out
.println((System.currentTimeMillis() - start) / 1000);
}
} catch (Throwable ex) {
System.out.println("Caught in run: " + ex);
ex.printStackTrace();
}
}
};
t.start();
// Give t time to get going...
Thread.sleep(100);
t.stop(); // EXPECT COMPILER WARNING
} catch (Throwable t) {
System.out.println("Caught in main: " + t);
t.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
简单的答案是jvm没有可靠的方法来阻止线程.要停止或中断线程,目标线程需要通过进入某些可中断状态(例如sleep()或wait())进行协作.
由于这个原因,不推荐使用Thread.stop()方法(其中包括).有关详细信息,请参阅http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html.
| 归档时间: |
|
| 查看次数: |
2445 次 |
| 最近记录: |