+/EE360P

distributed systems

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

jspspikeFinished 243d7a64

master
2.1 KiB80 linesraw
1// jkj858
2// jbr2558
3
4import java.util.concurrent.locks.*;
5
6public class FairUnifanBathroom {
7    final ReentrantLock monitor = new ReentrantLock();
8    final Condition ut = monitor.newCondition();
9    final Condition ou = monitor.newCondition();
10
11    boolean utIn = false;
12    int count = 0;
13    int ticketNumber = 0;
14    int ticket = 0;
15
16    public void enterBathroomUT() throws InterruptedException {
17        monitor.lock();
18        int myTicketNumber = ticketNumber++;
19
20        try {
21            while (myTicketNumber != ticket || (count != 0 && (!utIn || count >= 4))) {
22                System.out.println("UT Waiting " + myTicketNumber);
23                ut.await();
24            }
25            System.out.println("UT Entering " + myTicketNumber);
26            ticket++;
27            count++;
28            utIn = true;
29        } finally {
30            monitor.unlock();
31        } 
32    }
33
34    public void enterBathroomOU() throws InterruptedException {
35        monitor.lock();
36        int myTicketNumber = ticketNumber++;
37
38        try {
39            while (myTicketNumber != ticket || (count != 0 && (utIn || count >= 4))) {
40                System.out.println("OU Waiting " + myTicketNumber);
41                ou.await();
42            }
43            System.out.println("OU Entering " + myTicketNumber);
44            ticket++;
45            count++;
46            utIn = false;
47        } finally {
48            monitor.unlock();
49        }
50    }
51
52    public void leaveBathroomUT() {
53        monitor.lock();
54        count--;
55        if (count == 0) {
56            System.out.println("UT Leaving empty");
57            ut.signalAll();
58            ou.signalAll();
59        } else {
60            System.out.println("UT Leaving");
61            ut.signalAll();
62        }
63        monitor.unlock();
64    }
65
66    public void leaveBathroomOU() {
67        monitor.lock();
68        count--;
69        if (count == 0) {
70            System.out.println("OU Leaving empty");
71            ut.signalAll();
72            ou.signalAll();
73        } else {
74            System.out.println("OU Leaving");
75            ou.signalAll();
76        }
77
78        monitor.unlock();
79    }
80}