JAVA多线程-死锁
1.创建类:DeadLockDemo
public class DeadLockDemo {
/**
* 什么是死锁?
* 死锁是两个或两个以上的进程在执行过程中,因为争夺资源而造成一种相互等待锁的现象,如果没有外力干涉的情况下,他们无法再继续执行下去
*
* 产生死锁的原因:
* 1.系统资源不足
* 2.进行运行推进顺序不合适
* 3.资源分配不当
*
* 如何验证是否是死锁的情况?
*/
// 创建两个对象
static Object o1 = new Object();
static Object o2 = new Object();
public static void main(String[] args) {
new Thread(()->{
synchronized (o1){
System.out.println(Thread.currentThread().getName() + "持有锁o1,试图获取锁o2");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2){
System.out.println(Thread.currentThread().getName() + "获取锁o2");
}
}
},"aaa").start();
new Thread(()->{
synchronized (o2){
System.out.println(Thread.currentThread().getName() + "持有锁o2,试图获取锁o1");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1){
System.out.println(Thread.currentThread().getName() + "获取锁o1");
}
}
},"bbb").start();
}
}
2.查看进程号:jps 查看java进程
E:>jps
14496
17732 RemoteMavenServer36
23220 Jps
1624 jar
25416 KotlinCompileDaemon
27080 DeadLockDemo
24524 Launcher
3.查看线程运行状态:jstack 20040
点击查看代码
Found one Java-level deadlock:
=============================
"bbb":
waiting to lock monitor 0x15ec76c4 (object 0x05eef928, a java.lang.Object),
which is held by "aaa"
"aaa":
waiting to lock monitor 0x15ec9254 (object 0x05eef930, a java.lang.Object),
which is held by "bbb"
Java stack information for the threads listed above:
===================================================
"bbb":
at com.atguigu.springcloud.javautilconcurrent.juc.deadlock.DeadLockDemo.lambda$main$1(DeadLockDemo.java:57)
- waiting to lock <0x05eef928> (a java.lang.Object)
- locked <0x05eef930> (a java.lang.Object)
at com.atguigu.springcloud.javautilconcurrent.juc.deadlock.DeadLockDemo$$Lambda$2/13876619.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
"aaa":
at com.atguigu.springcloud.javautilconcurrent.juc.deadlock.DeadLockDemo.lambda$main$0(DeadLockDemo.java:43)
- waiting to lock <0x05eef930> (a java.lang.Object)
- locked <0x05eef928> (a java.lang.Object)
at com.atguigu.springcloud.javautilconcurrent.juc.deadlock.DeadLockDemo$$Lambda$1/33002191.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Found 1 deadlock.