多线程的死锁
- Java线程死锁是一个经典的多线程问题, 因为不同的线程都在等待根本不可能被释放的锁, 从而导致线程中的任务无法完成
- 下面演示互相等待对方锁释放的死锁
public class DealThread implements Runnable {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
//俩把锁
private final Object lock1 = new Object();
private final Object lock2 = new Object();
@Override
public void run() {
if ("a".equals(userName)) {
synchronized (lock1) {
System.out.println("userName=" + userName + " :" + "进入lock1");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("由lock1->进入->lock2");
}
}
}
if ("b".equals(userName)) {
synchronized (lock2) {
System.out.println("userName=" + userName + " :" + "进入lock2");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("由lock2->进入->lock1");
}
}
}
}
}
- 启动类
public class Run {
public static void main(String[] args) throws InterruptedException {
DealThread dealThread = new DealThread();
dealThread.setUserName("a");
Thread thread = new Thread(dealThread);
thread.start();
//注意这里是等待0.1秒 而线程是等待三秒
Thread.sleep(100);
dealThread.setUserName("b");
Thread thread1 = new Thread(dealThread);
thread1.start();
}
}
- 运行结果
此时我们发现已经进入死锁
用JDK检测死锁
在你安装JDK的bin目录下按住shift加鼠标右键启动powershell
输入
jps
命令
知道我们启动类中死锁的线程的线程id是14784
使用
jstack
命令在最后面获得信息
- 浏览信息知道出现死锁的代码行在哪, 和在等待什么锁导致的死锁都可以发现.