Prev | Current Page 287 | Next

Carl Reynolds and Paul Tymann

"Schaum's Outline of Principles of Computer Science"

util.*;
public class PC {
static final int MAXQUEUE = 5;
private List messages = new ArrayList();
// called by Producer
public 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;
}
}
CHAP. 6] OPERATING SYSTEMS 109
Here is code called PC_demo, along with code for Producer and Consumer thread classes, that
exercises the PC class as a monitor to synchronize activities:
public class PC_demo {
public static void main(String args[]) {
PC monitor = new PC();
Producer producer = new Producer( monitor );
Consumer consumer = new Consumer( monitor );
consumer.start();
producer.start();
}
}
public class Producer extends Thread {
PC monitor;
static final int MAXQUEUE = 5;
Producer( PC theMonitor ) {
monitor = theMonitor;
}
public void run() {
while ( true ) {
monitor.putMessage();
try { Thread.sleep( 1000 );
}catch(InterruptedException e){}
}
}
}
public class Consumer extends Thread {
PC monitor;
Consumer( PC theMonitor ) {
monitor = theMonitor;
}
public void run() {
while ( true ) {
String newMessage = monitor.


Pages:
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
miedzyzdroje hotel asus netbooki Chirurg łódź Namioty Mazury i interesująca cena Szkoły policealne fryzjer w warszawie