多線程生產者,消費者例題

   生產者、消費者問題

 生產者講產品交給電源,而消費者從店員出去走產品,店員一次只能持有固定數量的產品,

如果生產者生產了過多的產品,店員會叫生產者等一下,如果店中有空位放產品了在通知生產者繼續生產;如果店中沒有了產品,店員會告訴消費者等一下,如果店中有產品了再通知消費者取走產品。

問題:生產者比消費者快是,消費者會漏掉一些數據沒有取到

消費者比生產者快時,消費者會取相同的數據

  

//生產者線程要執行的任務
public class Producer implements Runnable {
	private Clerk cl;
	public Producer(Clerk cl){
		this.cl=cl;
	}

	public void run() {
		System.out.println("生產者開始生產產品!");
		while(true){
			try {
				Thread.sleep((int)(Math.random()*10)*100);
			} catch (InterruptedException e) {
				// TODO 自動生成的 catch 塊
				e.printStackTrace();
			}
			cl.addProduct();//生產產品
		}
	}
	
	
}
//消費者線程要執行的任務
public class Consumer implements Runnable {
	private Clerk cl;
  public Consumer(Clerk cl) {
		this.cl=cl;
	}
  
  
	public void run() {
		System.out.println("消費者開始取走產品!");
		while(true){
			try {
				Thread.sleep((int)(Math.random()*10)*100);
			} catch (InterruptedException e) {
				// TODO 自動生成的 catch 塊
				e.printStackTrace();
			}
			cl.getProduct();//取走產品
		}
	}

}
public class Clerk {
	private int product=0;//產品默認0;
	//生產者生成出來的產品交給店員
	public synchronized void addProduct(){
		if(this.product>=20){
			try {
				wait();//產品已滿,請稍等在生產
			} catch (InterruptedException e) {
				// TODO 自動生成的 catch 塊
				e.printStackTrace();
			}
		}else{
			product++;
			System.out.println("生產者生產地"+product+"個產品。");
			notifyAll(); //通知等待區的消費者今天取產品了
		}
	}
	
	//消費者從店員處取產品
	public synchronized void getProduct(){
		if(this.product<=0){
			try {
				wait();//產品沒有貨了,請稍等再取
			} catch (InterruptedException e) {
				// TODO 自動生成的 catch 塊
				e.printStackTrace();
			}
		}else{
			System.out.println("消費者取走了第"+product+"個產品");
			product--;
			notifyAll();//通知等待區的生成者可以生產 產品
		}
	}
}
public static void main(String[] args) {
		// TODO 自動生成的方法存根
			Clerk cl=new Clerk();
			Thread prt=new Thread(new Producer(cl));//生產者線程
			Thread cot=new Thread(new Consumer(cl));//消費者線程
			prt.start();
			cot.start();
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章