-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample111.java
More file actions
50 lines (41 loc) · 1.02 KB
/
Example111.java
File metadata and controls
50 lines (41 loc) · 1.02 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
// Example 111 from page 85
//
class Buffer {
private int contents;
private boolean empty = true;
public int get() {
synchronized (this) {
while (empty)
try { this.wait(); } catch (InterruptedException x) {};
empty = true;
this.notifyAll();
return contents;
} }
public void put(int v) {
synchronized (this) {
while (!empty)
try { this.wait(); } catch (InterruptedException x) {};
empty = false;
contents = v;
this.notifyAll();
} }
}
class Example111 {
public static void main(String[] args) {
final Buffer buf = new Buffer();
class Producer extends Thread {
@Override
public void run() {
for (int i=1; true; i++) {
buf.put(i);
Util.pause(10, 100);
} } }
class Consumer extends Thread {
@Override
public void run() {
for (;;)
System.out.println("Consumed " + buf.get());
} }
new Producer().start();
new Consumer().start(); new Consumer().start();
} }