forked from patniemeyer/learningjava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducer.java
More file actions
41 lines (35 loc) · 830 Bytes
/
Copy pathProducer.java
File metadata and controls
41 lines (35 loc) · 830 Bytes
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
import java.util.*;
public class Producer implements Runnable
{
static final int MAXQUEUE = 5;
private List messages = new ArrayList();
public void run() {
while ( true ) {
putMessage();
try {
Thread.sleep( 1000 );
} catch ( InterruptedException e ) { }
}
}
private synchronized void putMessage()
{
while ( messages.size() >= MAXQUEUE )
try {
wait();
} catch( InterruptedException e ) { }
messages.add( new java.util.Date().toString() );
notify();
}
// called by Consumer
public synchronized String getMessage()
{
while ( messages.size() == 0 )
try {
notify();
wait();
} catch( InterruptedException e ) { }
String message = (String)messages.remove(0);
notify();
return message;
}
}