-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnisexBathroom.java
More file actions
120 lines (107 loc) · 3.44 KB
/
UnisexBathroom.java
File metadata and controls
120 lines (107 loc) · 3.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package interview;
import java.util.concurrent.Semaphore;
public class UnisexBathroom {
static String WOMEN = "women";
static String MEN = "men";
static String NONE = "none";
String inUseBy = NONE;
int empsInBathroom = 0;
Semaphore maxEmps = new Semaphore(3);
void useBathroom(String name) throws InterruptedException {
System.out.println("\n" + name + " using bathroom. Current employees in bathroom = ") ;
Thread.sleep(3000);
System.out.println("\n" + name + " done using bathroom " + System.currentTimeMillis() );
}
void maleUseBathroom(String name) throws InterruptedException {
synchronized (this) {
while (inUseBy.equals(WOMEN)) {
this.wait();
}
maxEmps.acquire();
empsInBathroom++;
inUseBy = MEN;
}
useBathroom(name);
maxEmps.release();
synchronized (this) {
empsInBathroom--;
if (empsInBathroom == 0)
inUseBy = NONE;
this.notifyAll();
}
}
void femaleUseBathroom(String name) throws InterruptedException {
synchronized (this) {
while (inUseBy.equals(MEN)) {
this.wait();
}
maxEmps.acquire();
empsInBathroom++;
inUseBy = WOMEN;
}
useBathroom(name);
maxEmps.release();
synchronized (this) {
empsInBathroom--;
if (empsInBathroom == 0)
inUseBy = NONE;
this.notifyAll();
}
}
public static void runTest() throws InterruptedException {
final UnisexBathroom unisexBathroom = new UnisexBathroom();
Thread female1 = new Thread(new Runnable() {
public void run() {
try {
unisexBathroom.femaleUseBathroom("Lisa");
} catch (InterruptedException ie) {
}
}
});
Thread male1 = new Thread(new Runnable() {
public void run() {
try {
unisexBathroom.maleUseBathroom("John");
} catch (InterruptedException ie) {
}
}
});
Thread male2 = new Thread(new Runnable() {
public void run() {
try {
unisexBathroom.maleUseBathroom("Bob");
} catch (InterruptedException ie) {
}
}
});
Thread male3 = new Thread(new Runnable() {
public void run() {
try {
unisexBathroom.maleUseBathroom("Anil");
} catch (InterruptedException ie) {
}
}
});
Thread male4 = new Thread(new Runnable() {
public void run() {
try {
unisexBathroom.maleUseBathroom("Wentao");
} catch (InterruptedException ie) {
}
}
});
female1.start();
male1.start();
male2.start();
male3.start();
male4.start();
female1.join();
male1.join();
male2.join();
male3.join();
male4.join();
}
public static void main(String[] args) throws InterruptedException{
UnisexBathroom.runTest();
}
}