java 生產者消費者問題

今天想寫數據庫的一個應用的,因爲涉及到加鎖解鎖設計,我就查了查生產中消費者問題,自己寫了一下。

首先,有一個倉庫,也就是一個當做緩衝區的東西

public class WareHouse {
    private int products[];
    private String name;
    private int base = 0;
    private int top = 0;
    private int capacity;

    public WareHouse(int capacity, String name) {
        products = new int[capacity];
        this.name = name;
        this.capacity = capacity;
    }

    public synchronized int pop() {
        int product = 0;
        if (top == base) {
            try {
                System.out.println("倉庫空了,快點來生產啊");
                wait();
            } catch (InterruptedException e) {
                System.out.println("stop push");
            }
        }
        if(top!=base){
        product = products[top--];
        System.out.println("消費了一個產品"+product);
        notify();
        }
        return product;
    }

    public synchronized void push(int n) {
        if (top == capacity - 1) {
            try {
                System.out.println("倉庫滿了,快點來消費");
                wait();
            } catch (InterruptedException e) {
                System.out.println("stop push");
            }
        }
        products[++top] = n;
        System.out.println("生產了一個產品 "+n);
        notify();
    }

    public int[] getProducts() {
        return products;
    }

    public String getName() {
        return name;
    }

}

然後是生產者和消費者
public class Producer extends Thread {
    private int no;
    private WareHouse wareHouse;

    public Producer(int no, WareHouse house) {
        this.no = no;
        this.wareHouse = house;
    }

    @Override
    public void run() {
        this.excuteProduce();
    }

    private void excuteProduce() {
        int i = 0;
        while (true) {

            wareHouse.push(i);
           // System.out.println(no + "我生產了一個產品" + i);
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                return;
            }
            ++i;
        }
    }

}
public class Consumer extends Thread {
    private int no;
    private WareHouse wareHouse;

    public Consumer(int no, WareHouse house) {
        this.no = no;
        wareHouse = house;
    }

    @Override
    public void run() {
        excuteConsume();
    }

    private void excuteConsume() {
        while (true) {
            int n=this.wareHouse.pop();
           // System.out.println("我消費了"+n);
            try {
                Thread.sleep(1000);
            }catch (Exception e){
                return;
            }

        }
    }
}


發佈了37 篇原創文章 · 獲贊 4 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章