死锁编码与分析
程序员文章站
2022-03-02 14:14:19
...
死锁产生的主要原因:两个或两个以上进程在执行过程中,因争夺资源而造成的一种循环等待现象,若无外力干涉它们将无法推进下去
-
编码
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+" 尝试获得:"+lockB);
try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e){e.printStackTrace();}
synchronized (lockB){
System.out.println(Thread.currentThread().getName()+"\t 自己持有:"+lockB+" 尝试获得:"+lockA);
}
}
}
}
public class DeadLockDemo {
public static void main(String[] args) {
String str1="str1";
String str2="str2"; //两个资源
new Thread(new HoldLockThread(str1,str2),"AAA").start();
new Thread(new HoldLockThread(str2,str1),"BBB").start();
}
}
运行结果:
两个线程操纵两个资源 str1与str2,AAA线程获取str1的锁之后,进入休眠,此时BBB线程进来获取了str2的锁,尝试获取str1的锁,但是str1的锁被AAA线程占有,AAA线程苏醒,尝试获取str2的锁,str2被线程BBB占有,所以就出现了循环等待现象,就是死锁
- 定位分析
jps -l 命令查看运行程序进程号
D:\IntelliJIDEAproject\InterviewFirst>jps -l
2880 org.jetbrains.jps.cmdline.Launcher
3952 org.jetbrains.jps.cmdline.Launcher
13448 org.jetbrains.kotlin.daemon.KotlinCompileDaemon
15276 sun.tools.jps.Jps
15996 eight.DeadLockDemo
5996
jstack 进程号 命令定位分析 确认是死锁!
=============================
"BBB":
waiting to lock monitor 0x00000000033ab1a8 (object 0x00000000d5f7cda8, a java.lang.String),
which is held by "AAA"
"AAA":
waiting to lock monitor 0x00000000033a8868 (object 0x00000000d5f7cdd8, a java.lang.String),
which is held by "BBB"
Java stack information for the threads listed above:
===================================================
"BBB":
at eight.HoldLockThread.run(DeadLockDemo.java:21)
- waiting to lock <0x00000000d5f7cda8> (a java.lang.String)
- locked <0x00000000d5f7cdd8> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)
"AAA":
at eight.HoldLockThread.run(DeadLockDemo.java:21)
- waiting to lock <0x00000000d5f7cdd8> (a java.lang.String)
- locked <0x00000000d5f7cda8> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)
Found 1 deadlock.
上一篇: 输入字符串统计字符串中每个字符出现的次数
下一篇: 解决idea JSP路径错误问题