Java 生產者--消費者問題

Java 經典問題 生產者–消費者問題
現在有這樣一個問題,生產者不停的生產饅頭,消費者則不停的消費饅頭,同時我們把生產的饅頭存放到一個(籃子)即棧中。

有上面的描述,我可以抽出一下幾個類。
ManTou 饅頭類
StackBasket 籃子類(用於裝饅頭的類)
Producer 用於生產饅頭的類
Consumer 用於消費饅頭的類
ProducerAndConsumer 這個類爲測試類

/**
 * @author yikai
 * 饅頭類,就是一個實體類,就爲每一個饅頭設置一個id
 */
public class ManTou {
    int id;

    public ManTou(int id) {
        this.id = id;
    }
}
/**
 * @author yikai
 * 籃子類,設置爲一個棧結構,因此裏面設置一個push(壓棧)方法和一個pop(出棧)方法
 * 因爲涉及到藍子的大小,以及多線程修改饅頭數量的問題,所以要加上synchronized
 */
public class StackBasket {

    int index = 0;
    ManTou manTous[] = new ManTou[5];

    public synchronized void push(ManTou manTou) {
        while (index == 5){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        manTous[index] = manTou;
        index++;
        this.notify();
    }

    public synchronized ManTou pop() {
        while (index == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        index--;
        ManTou manTou = manTous[index];
        this.notify();
        return manTou;

    }
}
/**
 * @author yikai
 * 生產者與消費者類似,將生產的饅頭放入到籃子,所以需要一個籃子對象,然後調用籃子的
 * push方法,具體如下
 */
public class Producer implements Runnable {
    private StackBasket stackBasket;
    public Producer(StackBasket stackBasket) {
        this.stackBasket = stackBasket;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            ManTou manTou = new ManTou(i);
            stackBasket.push(manTou);
            System.out.println("producer: "+manTou.id);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
/**
 * @author yikai 
 * 消費者就是從籃子裏面不停的拿饅頭,所以需要一個籃子對象,然後從籃子對象中取饅頭
 * 具體如下代碼
 */
public class Consumer implements Runnable {

    private StackBasket stackBasket;

    public Consumer(StackBasket stackBasket){
        this.stackBasket = stackBasket;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            ManTou manTou = stackBasket.pop();
            System.out.println("consumer"+"  "+manTou.id);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
/**
 * @author yikai
 */
public class ProducerAndConsumer {


    public static void main(String[] arg) {
        StackBasket stackBasket = new StackBasket();
        Thread p = new Thread(new Producer(stackBasket));
        Thread c = new Thread(new Consumer(stackBasket));
        p.start();
        c.start();

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章