Java總裁-Java多線程

來源:互聯網
上載者:User

標籤: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多線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.