1. 程式人生 > 實用技巧 >生產者和消費者

生產者和消費者

管程法

利用緩衝區來解決生產者消費者問題

/**
 * 生產者消費者之管程法
 */
    public static void main(String[] args) {
        //緩衝區
        SynContainer synContainer = new SynContainer();
        new Producer(synContainer).start();
        new Consumer(synContainer).start();
    }
}

//產品
class Product {
    int id;

    public Product(int id) {
        this.id = id;
    }
}

//生產者
class Producer extends Thread {
    //緩衝區物件
    SynContainer container;

    public Producer(SynContainer container) {
        this.container = container;
    }

    //生產
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            //呼叫生產方法
            container.push(new Product(i));
            System.out.println("生產了" + i + "產品");
        }
    }
}

//消費者
class Consumer extends Thread {
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }
    //消費

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消費了" + container.pop().id + "產品");
        }
    }
}

//緩衝區
class SynContainer {
    //容器
    Product[] products = new Product[10];
    //容器計數器
    int count = 0;

    //生產者生產
    public synchronized void push(Product product) {
        //判斷是否已經達到生產滿了,滿了就等待,讓消費者消費
        if (count == products.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //開始生產並將產品放入容器
        products[count] = product;
        //計數
        count++;
        //通知消費者消費
        this.notifyAll();
    }

    //消費者消費(需要返回消費數量)
    public synchronized Product pop() {
        //判斷是否有產品可以消費,沒有就等待,通知生產者生產
        if (count == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //開始消費
        count--;
        //返回消費資訊
        Product product = products[count];
        //通知生產者生產
        this.notifyAll();
        return product;
    }