1编写死锁案列,运行
package com.thread.thread.deadLock;
public class DeadLockTest {
public static String objA = "strA";
public static String objB = "strB";
public static void main(String[] args){
Thread a = new Thread(new Lock1());
Thread b = new Thread(new Lock2());
a.start();
b.start();
}
}
class Lock1 implements Runnable{
@Override
public void run(){
try{
System.out.println("Lock1 running");
while(true){
synchronized(DeadLockTest.objA){
System.out.println("Lock1 lock strA");
Thread.sleep(3000);//获取strA后先等一会儿,让Lock2有足够的时间锁住strB
synchronized(DeadLockTest.objB){
System.out.println("Lock1 lock strB");
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
class Lock2 implements Runnable{
@Override
public void run(){
try{
System.out.println("Lock2 running");
while(true){
synchronized(DeadLockTest.objB){
System.out.println("Lock2 lock strB");
Thread.sleep(3000);
synchronized(DeadLockTest.objA){
System.out.println("Lock2 lock strA");
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
2 jps -v找到对应的线程 (对于安装了jvisualvm或者jconsole的也可以通过图形界面直接查看死锁的堆栈信息)
3jstack 7312 查看死锁的相关信息
可以看出thread-1锁住0x000000076f3b0308 等待0x000000076f3b02f0 与thread-0恰好相反