-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEarlyNotifyFix.java
More file actions
97 lines (77 loc) · 2.16 KB
/
Copy pathEarlyNotifyFix.java
File metadata and controls
97 lines (77 loc) · 2.16 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
package threadbook.ch08;
import java.util.*;
public class EarlyNotifyFix extends Object {
private List list;
public EarlyNotifyFix() {
list = Collections.synchronizedList(new LinkedList());
}
public String removeItem() throws InterruptedException {
print("in removeItem() - entering");
synchronized ( list ) {
while ( list.isEmpty() ) {
print("in removeItem() - about to wait()");
list.wait();
print("in removeItem() - done with wait()");
}
// extract the new first item
String item = (String) list.remove(0);
print("in removeItem() - leaving");
return item;
}
}
public void addItem(String item) {
print("in addItem() - entering");
synchronized ( list ) {
// There'll always be room to add to this List
// because it expands as needed.
list.add(item);
print("in addItem() - just added: '" + item + "'");
// After adding, notify any and all waiting
// threads that the list has changed.
list.notifyAll();
print("in addItem() - just notified");
}
print("in addItem() - leaving");
}
private static void print(String msg) {
String name = Thread.currentThread().getName();
System.out.println(name + ": " + msg);
}
public static void main(String[] args) {
final EarlyNotifyFix enf = new EarlyNotifyFix();
Runnable runA = new Runnable() {
public void run() {
try {
String item = enf.removeItem();
print("in run() - returned: '" +
item + "'");
} catch ( InterruptedException ix ) {
print("interrupted!");
} catch ( Exception x ) {
print("threw an Exception!!!\n" + x);
}
}
};
Runnable runB = new Runnable() {
public void run() {
enf.addItem("Hello!");
}
};
try {
Thread threadA1 = new Thread(runA, "threadA1");
threadA1.start();
Thread.sleep(500);
// start a *second* thread trying to remove
Thread threadA2 = new Thread(runA, "threadA2");
threadA2.start();
Thread.sleep(500);
Thread threadB = new Thread(runB, "threadB");
threadB.start();
Thread.sleep(10000); // wait 10 seconds
threadA1.interrupt();
threadA2.interrupt();
} catch ( InterruptedException x ) {
// ignore
}
}
}