我刚刚从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() 方法中放置一个 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();
}
}
最佳答案
简单的答案是 jvm 没有可靠的方法来停止线程。要停止或中断线程,目标线程需要通过进入某种可中断状态(例如 sleep() 或 wait())来进行协作。
Thread.stop() 方法已因这个原因(以及其他原因)而被弃用。参见 http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html了解更多详情。
关于java - 为什么 thread.stop() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4426592/