File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ 面试官:知道死锁嘛?
2+
3+ 我:知道,那我就谈一下Java的死锁吧,其实原理都一样。
4+
5+ 先看个例子:
6+
7+ ``` java
8+ public class Test {
9+ private static Object res1 = new Object ();
10+ private static Object res2 = new Object ();
11+
12+ public static void main (String [] args ) {
13+ new Thread (() - > {
14+ synchronized (res1) {
15+ System . out. println(Thread . currentThread(). getName() + " res1" );
16+ // 延迟一下, 确保B拿到了res2
17+ try { TimeUnit . SECONDS. sleep(1 ); } catch (InterruptedException e) { e. printStackTrace(); }
18+ synchronized (res2) {
19+ System . out. println(Thread . currentThread(). getName() + " res2" );
20+ }
21+ }
22+ }, " ThreadA" ). start();
23+
24+ new Thread (() - > {
25+ synchronized (res2) {
26+ System . out. println(Thread . currentThread(). getName() + " res2" );
27+ // 延迟一下,确保A拿到了res1
28+ synchronized (res1) {
29+ System . out. println(Thread . currentThread(). getName() + " res1" );
30+ }
31+ }
32+ }, " ThreadB" ). start();
33+ }
34+ }
35+ ```
36+
37+ 所以:死锁的条件?
38+
39+ - ** 互斥条件** :该资源任意一个时刻只由一个线程占用。(同一时刻,这个碗是我的,你不能碰)
40+ - ** 请求与保持条件** :一个进程因请求资源而阻塞时,对已获得的资源保持不放。(我拿着这个碗一直不放)
41+ - ** 不剥夺条件** :线程已获得的资源在末使用完之前不能被其他线程强行剥夺,只有自己使用完毕后才释放资源。(我碗中的饭没吃完,你不能抢,释放权是我自己的,我想什么时候放就什么时候放)
42+ - ** 循环等待条件** :若干进程之间形成一种头尾相接的循环等待资源关系。(我拿了A碗,你拿了B碗,但是我还想要你的B碗,你还想我的A碗)比喻成棒棒糖也阔以。
43+
44+ 面试官:所以解决死锁的办法是?
45+
46+ 我:好的,没毛病
47+
48+ - 预防死锁:
49+ - ** 资源一次性分配** :破坏请求和保持条件。
50+ - ** 可剥夺资源** :当进程新申请的资源不满足时,释放已经分配的资源。破坏不可剥夺条件
51+ - ** 资源有序分配** :系统给进程编号,按某一顺序申请资源,释放资源则反序释放。破坏循环等待条件。
52+ - 避免死锁:银行家算法:分配资源前先评估风险,会不会在分配后导致死锁。 即分配给一个进程资源的时候,该进程能否全部返还占用的资源。
53+ - 检测死锁:建立资源分配表和进程等待表。
54+ - 解除死锁:可以直接撤销死锁进程,或撤销代价最小的进程。
Original file line number Diff line number Diff line change 4949- [ 谈谈CAS] ( /Interview/sad/谈谈CAS.md )
5050- [ 谈谈ThreadLocal] ( /Interview/sad/谈谈ThreadLocal.md )
5151- [ 谈谈AQS] ( /Interview/sad/谈谈AQS.md )
52+ - [ 谈谈死锁] ( /Interview/sad/谈谈死锁.md )
5253
5354## 刷题系列
5455- [ 推荐:CS-Notes] ( https://cyc2018.github.io/CS-Notes/#/?id=✏️-算法 )
You can’t perform that action at this time.
0 commit comments