死锁
产生死锁的主要原因
- 系统资源不足
- 进程推进的顺序不合适
- 资源分配不合理
死锁产生Demo
package com.ctgu.juc;
import java.util.concurrent.TimeUnit;
class HoldLockThread implements Runnable{
private String lockA;
private String lockB;
public HoldLockThread(String lockA, String lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA){
System.out.println(Thread.currentThread().getName()+"\t持有 " + lockA);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB){
System.out.println(Thread.currentThread().getName()+"\t持有 " +lockB);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class DeadLock {
public static void main(String[] args) {
String lockA = "lockA";
String lockB = "lockB";
new Thread(new HoldLockThread(lockA,lockB),"A").start();
new Thread(new HoldLockThread(lockB,lockA),"B").start();
}
}
查看死锁故障
在Windows上,用idea的cmd窗口
jps -l :查看当前运行的进程
jstack 进程编号 :查看进程异常信息
例:
C:\Idea\JUC>jps -l
21584 com.ctgu.juc.DeadLock
8848 sun.tools.jps.Jps
15720
5592 org.jetbrains.jps.cmdline.Launcher
C:\Idea\JUC>jstack 21584
Java stack information for the threads listed above:
===================================================
"B":
at com.ctgu.juc.HoldLockThread.run(DeadLock.java:27)
- waiting to lock <0x00000000d6223198> (a java.lang.String)
- locked <0x00000000d62231d0> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)
"A":
at com.ctgu.juc.HoldLockThread.run(DeadLock.java:27)
- waiting to lock <0x00000000d62231d0> (a java.lang.String)
- locked <0x00000000d6223198> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)
Found 1 deadlock.
最底下有Java进行的总结:B在等A释放A锁,自身持有B锁;A在等B释放B锁,自身持有A锁
A和B互相等待获取对方的锁,但自身的锁又没有释放,也就导致了死锁的产生