1. 程式人生 > >生產者-消費者模型的java實現

生產者-消費者模型的java實現

生產者-消費者(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();
		}
	}
}

若有改進之處,望高手指正