问题:主进程开两条线程,一条线程生产,一条线程消费。要求生产者不能过度生产,即生产的产品有数量上限,假定就是5个,消费者不能过度消费,即不能没有了产品也在消费 。
Buffer类,用作缓冲区
import java.util.*;
public class Buffer {
private static final int BufferSize = 5;
private Vector<Object> buffer = new Vector<Object>(BufferSize);
private int objNum = 0;
public synchronized void in(Object obj) {
while (objNum == BufferSize) {
try {
this.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
buffer.add(obj);
objNum++;
if (objNum >= 1)
this.notifyAll();
}
public synchronized Object out() {
while (objNum == 0) {
try {
this.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
objNum--;
Object o = buffer.remove(0);
if(objNum <= 5)
this.notifyAll();
return o;
}
}
生产者和消费者类:
public class Producer implements Runnable{
private Buffer b = null;
public Producer(Buffer b) {
this.b = b;
}
public void run() {
for(int i = 0; i < 199; i++) {
synchronized(b) {
Object o = new Object();
b.in(o);
System.out.println("Producer " + i);
}
}
}
}
public class Consumer implements Runnable{
private Buffer b = null;
public Consumer(Buffer b) {
this.b = b;
}
public void run() {
for(int i = 0; i < 199; i++) {
synchronized(b) {
Object o = b.out();
System.out.println("Consumer " + i);
}
}
}
}
测试类:
public class TestDriver {
public static void main(String[] args) {
Buffer b = new Buffer();
Runnable p = new Producer(b);
Runnable c = new Consumer(b);
Thread producer = new Thread(p);
Thread consumer = new Thread(c);
producer.start();
consumer.start();
try {
producer.join();
consumer.join();
} catch(Exception e) {}
System.out.println("Test over");
}
}