KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Dining > Philosopher


1 //
2
// Copyright (C) 2005 United States Government as represented by the
3
// Administrator of the National Aeronautics and Space Administration
4
// (NASA). All Rights Reserved.
5
//
6
// This software is distributed under the NASA Open Source Agreement
7
// (NOSA), version 1.3. The NOSA has been approved by the Open Source
8
// Initiative. See the file NOSA-1.3-JPF at the top of the distribution
9
// directory tree for the complete NOSA document.
10
//
11
// THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY
12
// KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT
13
// LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO
14
// SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
15
// A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT
16
// THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT
17
// DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE.
18
//
19
/* Author: Masoud Mansouri-Samani
20  * Date: 15 Sept 2003
21  */

22
23 package DiningPhilosophers;
24
25 public class Philosopher extends Thread JavaDoc {
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 JavaDoc 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 JavaDoc 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 JavaDoc e) {
64         System.out.println(e);
65       }
66       System.out.println(num+" Finished thinking.");
67     }
68   }
69 }
70
Popular Tags