`
liuyes
  • 浏览: 53035 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用jvm thread dumps查看程序死锁

 
阅读更多

产生死锁测试代码如下:

package test;

public class DeathLockTest {
	private static final String A="a";
	private static final String B="b";
	
	public static void main(String[] args) {
		Thread t1 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				testA();
				
			}
		});
		Thread t2 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				testB();
				
			}
		});
		t1.start();
		t2.start();
	}
	
	public static void testA(){
		synchronized (A) {
			try {
				Thread.sleep(1100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized (B) {
				System.out.println("aaa->bbb");
			}
		}
	}
	
	public static void testB(){
		synchronized (B) {
			synchronized (A) {
				System.out.println("bbb->aaa");
			}
		}
	}
}

 

两个方法testA和testB中是典型的锁对象顺序不当产生的死锁

我们在命令行下运行这个程序,将会死锁,程序停止响应。

这时我们按下ctrl+break,输出的信息中其中有这么一段:

Java stack information for the threads listed above:
===================================================
"Thread-1":
        at test.DeathLockTest.testB(DeathLockTest.java:49)
        - waiting to lock <0x37a4d840> (a java.lang.String)      //等待<0x37a4d840>上的锁
        - locked <0x37a4d858> (a java.lang.String)                  //已锁定<0x37a4d858>
        at test.DeathLockTest$2.run(DeathLockTest.java:25)
        at java.lang.Thread.run(Unknown Source)
"Thread-0":
        at test.DeathLockTest.testA(DeathLockTest.java:41)
        - waiting to lock <0x37a4d858> (a java.lang.String)      //等待<0x37a4d858>上的锁
        - locked <0x37a4d840> (a java.lang.String)                  //已锁定<0x37a4d840>
        at test.DeathLockTest$1.run(DeathLockTest.java:12)
        at java.lang.Thread.run(Unknown Source)

Found 1 deadlock.

 可以很容易的看出两个线程互相等待对方锁定的对象,造成死锁

 

 

0
5
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics