Yurttas/PL/OOL/Java/F/07/02/DP00.java
Jump to navigation
Jump to search
1/**
2 * Copyright(C) 1998
3 * All Rights Reserved. Salih Yurttas, ZCubes, BitsOfCode Software Systems, Inc..
4 *
5 * Permission to use, copy, modify, and distribute this
6 * software and its documentation for EDUCATIONAL purposes
7 * and without fee is hereby granted provided that this
8 * copyright notice appears in all copies.
9 *
10 * @date : January 1, 1998.
11 * @author : Salih Yurttas.
12 */
13
14
15class Fork {
16
17 private boolean free = true;
18
19 synchronized void pickUp() {
20 while(!free) {
21 try {
22 wait();
23 }
24 catch(Exception e) {
25 Thread.currentThread().stop();
26 }
27 }
28 free = false;
29 }
30
31 synchronized void putDown() {
32 free = true;
33 notify();
34 }
35
36}
37
38class Philosopher implements Runnable {
39
40 private Fork a,
41 b;
42 int n;
43
44 Philosopher(int n,
45 Fork a,
46 Fork b) {
47 this.a = a;
48 this.b = b;
49 this.n = n;
50 }
51
52 public void run(){
53 while(true) {
54 a.pickUp();
55 b.pickUp();
56
57 System.out.println("Philosopherosopher " +
58 n +
59 " is eating");
60
61 b.putDown();
62 a.putDown();
63 }
64 }
65
66}
67
68class DP00 {
69
70 public static void main(String[] argv){
71 int size = 5;
72 Fork[] forks = new Fork[size];
73
74 for(int i=0; i<size; ++i)
75 forks[i] = new Fork();
76
77 for(int i=0; i<size; ++i ) {
78 Fork a = forks[i];
79 Fork b = forks[(i+1)%size];
80 Philosopher p;
81
82 if(i%2==0)
83 p = new Philosopher(i,
84 a,
85 b);
86 else
87 p = new Philosopher(i,
88 b,
89 a);
90 new Thread(p).start();
91 }
92 }
93
94}