1 22 23 package DiningPhilosophers; 24 25 public class Philosopher extends Thread { 26 private Fork left; 27 private Fork right; 28 private int num; 29 30 Philosopher(int num, Fork left, Fork right) { 31 this.num=num; 32 this.left = left; 33 this.right = right; 34 } 35 36 public void run() { 37 for (;;) { 38 System.out.println(num+" Hungry ..."); 39 left.grab(num); 40 try { 41 sleep(100); 42 } catch (InterruptedException e) { 43 System.out.println(e); 44 } 45 46 right.grab(num); 47 48 System.out.println(num+" Eating ..."); 49 try { 50 sleep((long) (Math.random() * 1000)); 51 } catch (InterruptedException e) { 52 System.out.println(e); 53 } 54 System.out.println(num+" Finished eating."); 55 56 left.release(num); 57 58 right.release(num); 59 60 System.out.println(num+" Thinking ..."); 61 try { 62 sleep((long) (Math.random() * 1000)); 63 } catch (InterruptedException e) { 64 System.out.println(e); 65 } 66 System.out.println(num+" Finished thinking."); 67 } 68 } 69 } 70 | Popular Tags |