Java死锁演示
在线程中嵌套获取锁导致死锁。思路,尽量不要嵌套获取锁。
package com.mozq.demo.demo;
public class DeadLockDemo {
private static String A = "A";
private static String B = "B";
public static void main(String[] args) {
new DeadLockDemo().deadLock();
}
private void deadLock() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (A) {
System.out.println("线程1获取A锁");
try { Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (B) {
System.out.println("1");
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (B) {
synchronized (A) {
System.out.println("2");
}
}
}
});
t1.start();
t2.start();
}
}
控制台输出
Connected to the target VM, address: '127.0.0.1:18103', transport: 'socket'
线程1获取A锁
jstack dump进程信息
C:\Program Files\Java\jdk1.8.0_181\bin>jstack 196408 > d:/00/02/dump1.txt
C:\Program Files\Java\jdk1.8.0_181\bin>netstat -ano | findstr 18103
TCP 127.0.0.1:18103 127.0.0.1:18104 ESTABLISHED 196408
TCP 127.0.0.1:18104 127.0.0.1:18103 ESTABLISHED 204140
C:\Program Files\Java\jdk1.8.0_181\bin>jstack 204140 > d:/00/02/dump1.txt
死锁信息
"Thread-1" #14 prio=5 os_prio=0 tid=0x00000000196f1000 nid=0x33cdc waiting for monitor entry [0x000000001aaff000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.mozq.demo.demo.DeadLockDemo$2.run(DeadLockDemo.java:30)
- waiting to lock <0x00000000d63716e0> (a java.lang.String)
- locked <0x00000000d6371710> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)
"Thread-0" #13 prio=5 os_prio=0 tid=0x00000000196e7800 nid=0x33898 waiting for monitor entry [0x000000001a9fe000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.mozq.demo.demo.DeadLockDemo$1.run(DeadLockDemo.java:20)
- waiting to lock <0x00000000d6371710> (a java.lang.String)
- locked <0x00000000d63716e0> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)
Found one Java-level deadlock:
=============================
"Thread-1":
waiting to lock monitor 0x0000000017f3bcc8 (object 0x00000000d63716e0, a java.lang.String),
which is held by "Thread-0"
"Thread-0":
waiting to lock monitor 0x0000000017f3fd68 (object 0x00000000d6371710, a java.lang.String),
which is held by "Thread-1"
Java stack information for the threads listed above:
===================================================
"Thread-1":
at com.mozq.demo.demo.DeadLockDemo$2.run(DeadLockDemo.java:30)
- waiting to lock <0x00000000d63716e0> (a java.lang.String)
- locked <0x00000000d6371710> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)
"Thread-0":
at com.mozq.demo.demo.DeadLockDemo$1.run(DeadLockDemo.java:20)
- waiting to lock <0x00000000d6371710> (a java.lang.String)
- locked <0x00000000d63716e0> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)
Found 1 deadlock.
bug
idea中运行main方法后,如何获取其对应的进程id?