《Cracking the Coding Interview》——第16章:线程与锁——题目3
生活随笔
收集整理的這篇文章主要介紹了
《Cracking the Coding Interview》——第16章:线程与锁——题目3
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2014-04-27 19:26
題目:哲學(xué)家吃飯問(wèn)題,死鎖問(wèn)題經(jīng)典模型(專門用來(lái)黑哲學(xué)家的?)。
解法:死鎖四條件:1. 資源互斥。2. 請(qǐng)求保持。3. 非搶占。4. 循環(huán)等待。所以,某磚家拿起一只筷子后如果發(fā)現(xiàn)沒(méi)有另一只了,就必須把手里這只筷子放下,這應(yīng)該是通過(guò)破壞“請(qǐng)求保持”原則來(lái)防止死鎖產(chǎn)生,請(qǐng)求資源失敗時(shí),連自己的資源也進(jìn)一步釋放,然后在下一輪里繼續(xù)請(qǐng)求,直到成功執(zhí)行。
代碼:
1 // This is the class for chopsticks. 2 import java.util.concurrent.locks.Lock; 3 import java.util.concurrent.locks.ReentrantLock; 4 5 public class Chopstick { 6 private Lock lock; 7 8 public Chopstick() { 9 lock = new ReentrantLock(); 10 } 11 12 public boolean pickUp() { 13 return lock.tryLock(); 14 } 15 16 public void putDown() { 17 lock.unlock(); 18 } 19 } 20 21 //------------------------------------I'm a delimiter------------------------------------ 22 // This is the class for philosophers. 23 import java.util.Vector; 24 25 public class Philosopher extends Thread { 26 private Chopstick left; 27 private Chopstick right; 28 private int id; 29 int appetite; 30 31 final int FULL_APPETITE = 10; 32 33 public Philosopher(Chopstick left, Chopstick right, int id) { 34 // TODO Auto-generated constructor stub 35 appetite = 0; 36 this.left = left; 37 this.right = right; 38 this.id = id; 39 } 40 41 private boolean pickUp() { 42 if (!left.pickUp()) { 43 return false; 44 } 45 if (!right.pickUp()) { 46 left.putDown(); 47 return false; 48 } 49 return true; 50 } 51 52 private void putDown() { 53 left.putDown(); 54 right.putDown(); 55 } 56 57 public boolean eat() { 58 while (appetite < FULL_APPETITE) { 59 if (!pickUp()) { 60 return false; 61 } 62 System.out.println(id + ":chew~"); 63 ++appetite; 64 putDown(); 65 } 66 return appetite == FULL_APPETITE; 67 } 68 69 @Override 70 public void run() { 71 // TODO Auto-generated method stub 72 super.run(); 73 while (!eat()) { 74 // Not full yet. 75 } 76 } 77 78 public static void main(String[] args) { 79 final int n = 6; 80 Vector<Chopstick> chopsticks = new Vector<Chopstick>(); 81 Vector<Philosopher> philosophers = new Vector<Philosopher>(); 82 83 for (int i = 0; i < n; ++i) { 84 chopsticks.add(new Chopstick()); 85 } 86 for (int i = 0; i < n; ++i) { 87 philosophers.add(new Philosopher(chopsticks.elementAt(i), 88 chopsticks.elementAt((i + 1) % n), i + 1)); 89 } 90 91 for (int i = 0; i < n; ++i) { 92 philosophers.elementAt(i).start(); 93 } 94 } 95 }?
轉(zhuǎn)載于:https://www.cnblogs.com/zhuli19901106/p/3695085.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的《Cracking the Coding Interview》——第16章:线程与锁——题目3的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 菏泽明丰理想城楼盘地址在哪里?
- 下一篇: 阿坝州嘉绒锦绣尚城楼盘地址在哪里?