KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > DiningPhilosophers > Fork


1 /* This file is part of the Java Pathfinder (JPF) distribution from
2  * NASA Ames Research Center. See file LICENSE for usage terms.
3  * (C) 1999,2003 NASA Ames Research Center
4  */

5
6 /* Author: Masoud Mansouri-Samani
7  * Date: 15 Sept 2003
8  */

9
10 package DiningPhilosophers;
11
12 public class Fork {
13   private boolean free;
14   private int num;
15
16   Fork(int n) {
17     free = true;
18     this.num = n;
19   }
20
21   synchronized void grab(int phil) {
22     while (!free) {
23       try {
24         wait();
25       } catch (InterruptedException JavaDoc e) {
26         System.out.println(e);
27       }
28     }
29     free = false;
30     System.out.println(phil+" Grabbed fork#: "+num);
31   }
32
33   synchronized void release(int phil) {
34     free = true;
35     notify();
36     System.out.println(phil+" Released fork#: "+num);
37   }
38 }
39
Popular Tags