Java:排查死锁:修订间差异

来自WHY42
imported>Soleverlee
无编辑摘要
imported>Soleverlee
无编辑摘要
 
第70行: 第70行:


然后通过jstack命令查看:
然后通过jstack命令查看:
[[Image:Jstack.png|600px]]
[[Image:Jstack.png|600px]]


[[Category:Programe]]
[[Category:Programe]]

2016年4月19日 (二) 09:28的最新版本

当多个对象互相等待对方释放锁时,可能出现死锁情况。可以通过JDK提供的工具查看死锁

public static void main(String[] args) {
	T1 t = new T1("A");
	Thread t1 = new Thread(t);
	t1.start();
	
	try {
		Thread.sleep(100);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	t.setA("B");
	Thread t2 = new Thread(t);
	t2.start();
	System.out.println("End");
}

static class T1 implements Runnable{
	String a = "";
	public T1(String a){
		this.a = a;
	}
	
	public String getA() {
		return a;
	}
	public void setA(String a) {
		this.a = a;
	}

	Object l1 = new Object();
	Object l2 = new Object();
	@Override
	public void run(){
		if("A".equals(this.a)){
			System.out.println("=>A");
			synchronized (l1) {
				System.out.println("l1");
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (l2) {
					System.out.println("l1->l2");
				}
			}
		}
		else if("B".equals(this.a)){
			System.out.println("=>B");
			synchronized (l2) {
				System.out.println("l2");
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (l1) {
					System.out.println("l2->l1");
				}
			}
		}
	}
}

先通过jps命令查看java进程,找到进程号:

然后通过jstack命令查看: