多线程系列之哲学家进餐

1 package thread; java.util.Random; 同时满足以下四个条件时,就会发生死锁 7 * 1. 互斥条件:线程使用的资源中至少有一个是不能共享的.这里,一根筷子一次就只能 8 * 被一个哲学家使用. 9 * 2. 至少有一个线程持有一个资源,并且它在等待获取一个当前被别的线程持有的资源.也就是 10 * 说,要放生死锁,哲学家必须拿着一根筷子并且等待另一根. 11 * 3. 资源不能被进程(线程)抢占.所有的进程必须把资源释放作为普通条件.哲学家很有礼貌, 12 * 不会从其他哲学家那里抢筷子. 13 * 4. 必须有循环等待,这时,一个进程等待其他进程持有的资源,后者又在等待另外一个进程持有的 14 * 资源,这样一直下去,直到有一个进程在等待第一个进程(线程)持有的资源,使得大家都被锁住. 15 * 在这里,以为每个哲学家都试图先得到左边的筷子,然后得到右边的筷子,所以发生了循环等待. 16 * 在下面的例子中,针对最后一个哲学家,通过交换构造器中的初始化顺序,打破了死锁条件,使得 17 * 最后一个哲学家先拿右边的筷子,再拿左边的筷子. Chopstick {counter = 0;number = counter++; String toString() { 24return “Chopstick ” + number; 25 } 26 }Philosopher extends Thread {Random rand = new Random();counter = 0;number = counter++; 32private Chopstick leftChopstick; 33private Chopstick rightChopstick;ponder = 0; Philosopher(Chopstick left, Chopstick right) { 37leftChopstick = left; 38rightChopstick = right; 39 start(); 40 } think() { 43System.out.println(this + ” thinking”); 44if (ponder > 0) 45try { 46 sleep(rand.nextInt(ponder)); 47} catch (InterruptedException e) { RuntimeException(e); 49 } 50 } eat() { 53synchronized (leftChopstick) { 54System.out.println(this + ” has ” + this.leftChopstick 55+ ” Waiting for ” + this.rightChopstick); 56synchronized (rightChopstick) { 57System.out.println(this + ” eating”); 58 } 59 } 60 } String toString() { 63return “Philosopher ” + number; 64 } run() { 67while (true) { 68 think(); 69 eat(); 70 } 71 } 72 } DiningPhilosophers { main(String[] args) { 76args = new String[4];args[1] = “0”; args[2] = “deadlock”; Philosopher[] philosopher = new Philosopher[Integer.parseInt(args[0])]; 82Philosopher.ponder = Integer.parseInt(args[1]);Chopstick left = new Chopstick(), right = new Chopstick(), first = left; 86int i = 0; 87while (i < philosopher.length – 1) { 88philosopher[i++] = new Philosopher(left, right); 89left = right; 90right = new Chopstick(); 91 }(args[2].equals(“deadlock”)) 94philosopher[i] = new Philosopher(left, first);philosopher[i] = new Philosopher(first, left); 98 99 }100 } // /:~

,其实你已经错过了旅行的意义。

多线程系列之哲学家进餐

相关文章:

你感兴趣的文章:

标签云: