文章放置于:https://github.com/zgkaii/CS-Notes-Kz,欢迎批评指正!
1 死锁定义
死锁是指,两个或两个以上的线程在执行过程中,由于竞争资源而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。简化一点说就是:一组相互竞争资源的线程因为互相等待,导致“永久”阻塞的现象。
例如下面案例:
public class DeadLockTest {
private static String A = "A";
private static String B = "B";
public static void main(String[] args) {
new DeadLockTest().deadLock();
}
private void deadLock() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (A) {
System.out.println("t1成功获取A锁");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (B) {
System.out.println("t1成功获取B锁");
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (B) {
System.out.println("t2成功获取B锁");
synchronized (A) {
System.out.println("t2成功获取A锁");
}
}
}
});
t1.start();
t2.start();
}
}
t1锁住了A,然后尝试对B进行加锁,同时t2已经锁住了B,接着尝试对A进行加锁,这时死锁就发生了。t1永远得不到B,t2也永远得不到A,它们将永远阻塞下去。
Thread 1 locks A, waits for B
Thread 2 locks B, waits for A
可以使用 jps 定位进程 id,再用 jstack 定位死锁。
D:\workplace\GiteeProjects\java-learn\concurrent-learn\src\main\java\com\kai\demo\basic>jps
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=gb2312
21812 Jps
15848 RemoteMavenServer36
25132 KotlinCompileDaemon
25580
27516 DeadLockTest
29052 Launcher
D:\workplace\GiteeProjects\java-learn\concurrent-learn\src\main\java\com\kai\demo\basic>jstack 27516
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=gb2312
2020-10-31 17:27:38
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.261-b12 mixed mode):
"DestroyJavaVM" #14 prio=5 os_prio=0 tid=0x0000016945db5000 nid=0xfd0 waiting on condition [0x0000000000000000]