根据java的sdk说明,当调用一个线程的stop时(暂时不管该不该使用该方法),线程会立即退出,但是下面的却没有,是什么原因呢?
-
package java_jni;
-
public class Main {
-
public static void main(String []args){
-
try {
-
Thread t = new Thread() {
-
public synchronized void run() {
-
try {
-
Thread.sleep(100000);
-
} 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();
-
}
-
}
-
}
运行该程序,然后用jstack输出堆栈;结果如下:为了方便,我只留下main 和 thread0的堆栈信息;
-
"Thread-0" prio=10 tid=0x00007f31240aa000 nid=0x1408 waiting on condition [0x00007f3121fe0000]
-
java.lang.Thread.State: TIMED_WAITING (sleeping)
-
at java.lang.Thread.sleep(Native Method)
-
at java_jni.Main$1.run(Main.java:16)
-
- locked <0x00000000d70e5be8> (a java_jni.Main$1)
-
-
-
-
"main" prio=10 tid=0x00007f3124007800 nid=0x13fb waiting for monitor entry [0x00007f312bf79000]
-
java.lang.Thread.State: BLOCKED (on object monitor)
-
at java.lang.Thread.stop1(Thread.java:819)
-
- waiting to lock <0x00000000d70e5be8> (a java_jni.Main$1)
-
at java.lang.Thread.stop(Thread.java:758)
-
at java_jni.Main.main(Main.java:26)
由上可见,main线程中调用t.stop的时候在等一个所,而这个锁被thread-0 锁住了。再次阅读源码,发现上面实现的run方法,前面有了
synchronized; 而在看看java的源码:果然如此;
-
@Deprecated
-
public final void stop() {
-
// If the thread is already dead, return.
-
// A zero status value corresponds to "NEW".
-
if ((threadStatus != 0) && !isAlive()) {
-
return;
-
}
-
stop1(new ThreadDeath());
-
}
-
-
private final synchronized void stop1(Throwable th) {
阅读(8028) | 评论(0) | 转发(0) |