標籤:java 多線程 並發 生產者消費者問題
記得第一次做java的題的時候,看到“寫出生產者消費者問題”,還以為是和原廠模式有關係。現在想想也是被雷倒了。
java的生產者消費者問題其實是講多線程並行作業同一資源緩衝區,當資源緩衝區滿的時候,線程繼續添加資料,則應該使其等待,有空間時再發訊息通知;當資源緩衝區沒有資源,線程繼續取資料時,應該使其等待,有資源是再發訊息通知;
先看一下運行:
以下是代碼:
Main.java:(主類)
package com.vrinux.setandget;public class Main { public static void main(String[] args) { // TODO Auto-generated method stub //建立商店對象,並設定最大容量為10; Store store = new Store(10); //建立兩個生產者; Pro pro1 = new Pro(store); Pro pro2 = new Pro(store); //建立三個消費者; Coner coner1 = new Coner(store); Coner coner2 = new Coner(store); Coner coner3 = new Coner(store); //啟動線程; pro1.start(); pro2.start(); coner1.start(); coner2.start(); coner3.start(); }}
Store.java:(商店類)
package com.vrinux.setandget;public class Store { //靜態變數,商店的最大儲存值; private final int max; //商店儲存的初始值;為0; private int count; //構造器; public Store(int max) { this.max = max; this.count = 0; } //進貨的方法,【注意】要用synchronized修飾,這是同步鎖, public synchronized void add() { //判斷商店儲存數量是否已滿;是則讓生產者等待; while(count>=max){ System.out.println("倉庫已滿,請稍再後入貨~"); try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //沒有滿,則進貨1; count += 1; //列印當前庫存; System.out.println("當前庫存為"+count); //通知所有生產者,可以進貨; this.notifyAll(); } //消費的方法,【注意】要用synchronized修飾,這是同步鎖, public synchronized void remove() { //判斷商店庫存是否沒貨,是則讓消費者等待; while(count<=0){ System.out.println("倉庫缺貨,請稍後再取貨~"); try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //否則,消費1; count -= 1; //列印庫存; System.out.println("當前庫存為"+count); //通知所有消費者來消費; this.notifyAll(); }}
Pro.java:(生產者)
package com.vrinux.setandget;public class Pro extends Thread{ private Store store; public Pro(Store store){ this.store = store; } @Override public void run() { // TODO Auto-generated method stub while(true){ //向store進貨,並休眠; store.add(); try { Thread.sleep(610); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}
Coner.java:(消費者)
package com.vrinux.setandget;public class Coner extends Thread { private Store store; public Coner(Store store) { this.store = store; } @Override public void run() { // TODO Auto-generated method stub while (true) { //從store消費,並休眠; store.remove(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}
java:生產者消費者問題