-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCubbyHole.java
More file actions
53 lines (40 loc) · 1.26 KB
/
Copy pathCubbyHole.java
File metadata and controls
53 lines (40 loc) · 1.26 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
package threadbook.ch08;
public class CubbyHole extends Object {
private Object slot;
public CubbyHole() {
slot = null; // null indicates empty
}
public synchronized void putIn(Object obj)
throws InterruptedException {
print("in putIn() - entering");
while ( slot != null ) {
print("in putIn() - occupied, about to wait()");
wait(); // wait while slot is occupied
print("in putIn() - notified, back from wait()");
}
slot = obj; // put object into slot
print("in putIn() - filled slot, about to notifyAll()");
notifyAll(); // signal that slot has been filled
print("in putIn() - leaving");
}
public synchronized Object takeOut()
throws InterruptedException {
print("in takeOut() - entering");
while ( slot == null ) {
print("in takeOut() - empty, about to wait()");
wait(); // wait while slot is empty
print("in takeOut() - notified, back from wait()");
}
Object obj = slot;
slot = null; // mark slot as empty
print(
"in takeOut() - emptied slot, about to notifyAll()");
notifyAll(); // signal that slot is empty
print("in takeOut() - leaving");
return obj;
}
private static void print(String msg) {
String name = Thread.currentThread().getName();
System.out.println(name + ": " + msg);
}
}