生产者和消费者是操作系统中的一个经典问题,这个问题是在讲“进程同步”时的一个例子,下面我就用Java语言中的notify和wait关键字实现这个算法。
生产者
/**
* Description: 生产者.
*
* @author: crane-yuan
* @date: 2016年11月5日 下午3:27:46
*/
public class Producer extends Thread
{
static final int MAXQUEUE = 10;
private Vector messages = new Vector();
/**
* Description:
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
while (true) {
putMessage();
sleep(1500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private synchronized void putMessage() throws InterruptedException {
while (messages.size() == MAXQUEUE) {
wait();
}
messages.add(new Date().toLocaleString());
System.out.println("put message...");
notify();
}
//Called by Consumer
public synchronized String getMessage() throws InterruptedException {
notify();
while (messages.size() == 0) {
wait();
}
String message = (String) messages.firstElement();
messages.remove(message);
return message;
}
}
消费者
/**
* Description: 消费者.
*
* @author: crane-yuan
* @date: 2016年11月5日 下午3:39:11
*/
public class Consumer extends Thread
{
Producer producer;
Consumer(Producer p) {
producer = p;
}
/**
* Description:
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
while (true) {
String message = producer.getMessage();
System.out.println("Got message: "+message);
sleep(2000);
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Producer producer = new Producer();
producer.start();
new Consumer(producer).start();
}
}
结果
put message...
Got message: 2016-11-5 17:06:28
put message...
Got message: 2016-11-5 17:06:30
put message...
Got message: 2016-11-5 17:06:32
put message...
put message...
Got message: 2016-11-5 17:06:33
put message...
Got message: 2016-11-5 17:06:35
put message...
Got message: 2016-11-5 17:06:36
put message...
put message...
Got message: 2016-11-5 17:06:38