標籤:private product public 消費者 多線程
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 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 Demo {
}
public class Main {
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();
}
}
Java總裁-Java多線程