23Java多线程之死锁

推荐链接:

Java 实例 - 死锁及解决方法 - 菜鸟

概述

死锁:两个(或两个以上)线程在执行的过程中,因争夺资源产生的一种互相等待现象。

产生条件:

  • 两个(或两个以上)线程
  • 两个(或两个以上)锁
  • 两个(或两个以上)线程持有不同锁
  • 争夺对方的锁

编写死锁代码

synchronized嵌套

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Test {
public static void main(String[] args) {
Thread threadA = new Thread(new LockA());
Thread threadB = new Thread(new LockB());
threadA.start();
threadB.start();
}
}

class LockA implements Runnable {
@Override
public void run() {
printA();
}

public static synchronized void printA() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("A");
// 持有类锁(LockA.class),争夺对方的锁(LockB.class)
LockB.printB();
}
}

class LockB implements Runnable {
@Override
public void run() {
printB();
}

public static synchronized void printB() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("B");
// 持有类锁(LockB.class),争夺对方的锁(LockA.class)
LockA.printA();
}
}

Lock未主动释放锁

Semaphore信号嵌套