使用jstack 发现死锁

参考:http://blog.chinaunix.net/uid-20104447-id-4075333.html

1. 据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) {




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值