生产者-消费者(producer-consumer)问题,也称作有界缓冲区(bounded-buffer)问题,两个进程共享一个公共的固定大小的缓冲区。其中一个是生产者,用于将消息放入缓冲区;另外一个是消费者,用于从缓冲区中取出消息。问题出现在当缓冲区已经满了,而此时生产者还想向其中放入一个新的数据项的情形,其解决方法是让生产者此时进行休眠,等待消费者从缓冲区中取走了一个或者多个数据后再去唤醒它。同样地,当缓冲区已经空了,而消费者还想去取消息,此时也可以让消费者进行休眠,等待生产者放入一个或者多个数据时再唤醒它。
public class Buffer {
private int maxsize =10;
private List<String> bufflist;
// private final Object ob =new Object();
public Buffer(){
bufflist = new ArrayList<>();
System.out.println("缓冲器初始化完毕!");
}
public void add(String name,String s){
synchronized (this) {
while(bufflist.size()==maxsize)
try {
System.out.println(name+"等待");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
bufflist.add(s);
System.out.println(name+"生产了一块面包!剩余"+bufflist.size()+"个");
notifyAll();
}
}
public synchronized void delete(String name){
synchronized (this) {
while(bufflist.isEmpty())
try {
System.out.println(name+"等待");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
bufflist.remove(0);
System.out.println(name+"买走了一块面包!剩余"+bufflist.size()+"个");
notifyAll();
}
}
}
public class Producer implements Runnable{
private Buffer buffer;
private String name;
public Producer(Buffer buffer,String name){
this.buffer = buffer;
this.name = name;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
buffer.add(name,"bread");
}
}
}
public class Consumer implements Runnable{
private Buffer buffer;
private String name;
public Consumer(Buffer buffer,String name){
this.buffer = buffer;
this.name = name;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
buffer.delete(name);
}
}
}
public class Producer_Consumer {
public static void main(String[] args) {
Buffer buffer = new Buffer();
for(int i = 0;i<5; i++){
Runnable pro = new Producer(buffer, "生产者p"+(i+1));
Runnable con = new Consumer(buffer, "消费者c"+(i+1));
Thread producer = new Thread(pro);
Thread consumer = new Thread(con);
producer.start();
consumer.start();
}
}
}
若有改进之处,望高手指正