Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

生產者與消費者經典實作:用 wait/notifyAll 調度有限的倉庫

問題描述

生產者不斷把產品放進倉庫,消費者不斷從倉庫取走產品。生產者與消費者都可以有多個,而倉庫容量有限:庫滿時不能放,庫空時不能取。這兩句話就是整個問題的核心,也是 wait/notify 的教科書場景。

產品與角色

/**
 * 產品類別
 */
class Product {
    private String id;      // 產品 id
    private String name;    // 產品名稱

    public Product(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "(產品ID:" + id + " 產品名稱:" + name + ")";
    }

    public String getId()              { return id; }
    public void setId(String id)       { this.id = id; }
    public String getName()            { return name; }
    public void setName(String name)   { this.name = name; }
}

/**
 * 消費者
 */
class Consumer implements Runnable {
    private Storage storage;

    public Consumer(Storage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        storage.pop();
    }
}

/**
 * 生產者
 */
class Producer implements Runnable {
    private Storage storage;

    public Producer(Storage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        Product product = new Product("090505105", "電話");
        storage.push(product);
    }
}

倉庫:整個範例的心臟

/**
 * 倉庫
 */
class Storage {

    private Product[] products = new Product[10];   // 容量為 10
    private int top = 0;

    // 生產者放入產品
    public synchronized void push(Product product) {
        while (top == products.length) {
            try {
                wait();                 // 倉庫已滿,等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        products[top++] = product;
        System.out.println(Thread.currentThread().getName() + " 生產了產品 " + product);
        notifyAll();                    // 喚醒等待執行緒
    }

    // 消費者取出產品
    public synchronized Product pop() {
        while (top == 0) {
            try {
                wait();                 // 倉庫空,等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        --top;
        Product p = new Product(products[top].getId(), products[top].getName());
        products[top] = null;           // 協助 GC 回收
        System.out.println(Thread.currentThread().getName() + " 消費了產品 " + p);
        notifyAll();
        return p;
    }
}

啟動

public class ProducersAndConsumers {
    public static void main(String[] args) {
        Storage storage = new Storage();

        Thread consumer = new Thread(new Consumer(storage));
        consumer.setName("消費者");

        Thread producer = new Thread(new Producer(storage));
        producer.setName("生產者");

        consumer.start();
        producer.start();
    }
}

執行結果如預期:生產者先放,消費者再取。

生產者 生產了產品(產品ID:090505105 產品名稱:電話)
消費者 消費了產品(產品ID:090505105 產品名稱:電話)

四個非寫不可的細節

一、wait 必須包在 while 而不是 if 裡。被 notifyAll() 喚醒不代表條件已經成立——它只代表「有機會再檢查一次」。多個生產者同時被喚醒時,第一個搶到鎖把倉庫填滿,後面幾個若用 if 就會直接往下寫入,造成越界。用 while 才能重新驗證。

二、push 與 pop 都必須 synchronized。它們操作同一份共享狀態(陣列與 top),而 wait() 本身也只能在持有該物件鎖的同步區塊中呼叫,否則丟 IllegalMonitorStateException。

三、用 notifyAll 而非 notify。notify() 只喚醒一條,若剛好喚醒的是同類型的執行緒,而條件仍不滿足,全體就會一起卡死。用 notifyAll() 讓大家醒來各自用 while 判斷,雖然稍耗資源,卻安全得多。

四、取出後把位置設為 null。陣列仍持有產品物件引用,不主動清掉就無法被回收,長時間運行下是常見的記憶體洩漏來源。

理解這份範例之後,你會發現 java.util.concurrent 中的 BlockingQueue 其實就是它的工業化版本——把上面四個細節都替你處理好了。先手寫一次,再用標準庫,概念才真的吃得透。

Copyright © Linux教程網 All Rights Reserved