什么是死锁?
话不多说,上定义
死锁是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程。
知道了死锁定义,那么下面简单写一个死锁的例子
class HoldThread implements Runnable{
private String strA;
private String strB;
public HoldThread(String strA, String strB) {
this.strA = strA;
this.strB = strB;
}
@Override
public void run() {
synchronized(strA){
System.out.println(Thread.currentThread().getName()+"持有"+strA+"尝试获取"+strB);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (strB){
System.out.println(Thread.currentThread().getName()+"持有"+strB);
}
}
}
}
调用
public static void main(String[] args) {
String strA = "StrA";
String strB = "StrB";
new Thread(new HoldThread(strB,strA),"1").start();
new Thread(new HoldThread(strA,strB),"2").start();
}
运行结果
使用命令 jps -l 显示出当前后台进程id以及哪个类
使用 jstack 进程id 查看运行信息