生产者与消费者

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;

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值