+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

Wei-Lun Hungadd chap. 2 and 3df69975

master
1.1 KiB40 linesraw
1class DiningMonitor implements Resource {
2    int n = 0;
3    int state[] = null;
4    static final int thinking = 0, hungry = 1, eating = 2;
5    public DiningMonitor(int initN) {
6        n = initN;
7        state = new int[n];
8        for (int i = 0; i < n; i++) state[i] = thinking;
9    }
10    int left(int i) {
11        return (n + i - 1) % n;
12    }
13    int right(int i) {
14        return (i + 1) % n;
15    }
16    public synchronized void acquire(int i) {
17        state[i] = hungry;
18        test(i);
19        while (state[i] != eating)
20            Util.myWait(this);
21    }
22    public synchronized void release(int i) {
23        state[i] = thinking;
24        test(left(i));
25        test(right(i));
26    }
27    void test(int i) {
28        if ((state[left(i)] != eating) &&
29        (state[i] == hungry) &&
30        (state[right(i)] != eating)) {
31            state[i] = eating;
32            notifyAll();
33        }
34    }
35    public static void main(String[] args) {
36        DiningMonitor dm = new DiningMonitor(5);
37        for (int i = 0; i < 5; i++)
38            new Philosopher(i, dm);
39    }
40}