生產者與消費者

package com.zqb.bean3;

public class Test07 {

    public static void main(String[] args) {

        AppleBox ab = new AppleBox();

        Produce p = new Produce(ab);

        Consumer c = new Consumer(ab);

        Thread t = new Thread(p);

        t.start();

        Thread t2 = new Thread(c);

        t2.start();

    }

}

// 生產者
class Produce implements Runnable {

    AppleBox appleBox;

    public Produce(AppleBox appleBox) {

        this.appleBox = appleBox;

    }

    @Override

    public void run() {

        // 生產10個蘋果到AppleBox中

        for (int i = 1; i <= 10; i++) {

            Apple a = new Apple(i);

            appleBox.deposite(a);

            System.out.println(Thread.currentThread().getName() + "生產了" + a);

            try {

                Thread.sleep((int) Math.random() * 10000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

}

// 消費者

class Consumer implements Runnable {

    AppleBox appleBox;

    public Consumer(AppleBox appleBox) {

        this.appleBox = appleBox;

    }

    @Override

    public void run() {

        // 消費10個蘋果

        for (int i = 1; i <= 10; i++) {

            Apple a = appleBox.withdraw();

            System.out.println(Thread.currentThread().getName() + "消費了" + a);

            try {

                Thread.sleep((int) Math.random() * 10000);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

}

class AppleBox {

    int index = 0;

    Apple[] apples = new Apple[5];

    public synchronized void deposite(Apple apple) {

        // 判斷apples是否滿了,滿了,則不能再存

        while (index >= apples.length) {

            try {

                wait();

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

        // 沒滿則存

        notifyAll();

        apples[index] = apple;

        index++;

    }

    public synchronized Apple withdraw() {

        // 判斷apples是否空了,空了,則不能再取

        while (index == 0) {

            try {

                wait();

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

        // 沒空則取

        notifyAll();

        Apple a = apples[index - 1];

        index--;

        return a;

    }

}

class Apple {

    int id;

    Apple(int id) {

        this.id = id;

    }

    public String toString() {

        return "apple" + id;

    }

}

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