java多线程之--多的生产者与多个消费者

package com.qianfeng.day22_Thread;

/*
 * 多个生产者和多个消费者,包子数量最多5个,给包子编号,要求随机消费
 */
public class Demo04 {

    public static void main(String[] args) {
        Produce04 p = new Produce04();
        Customer04 c = new Customer04();
        Thread t1 = new Thread(p, "生产者1");
        Thread t2 = new Thread(p, "生产者2");
        Thread t3 = new Thread(p, "生产者3");
        Thread t4 = new Thread(c, "消费者1");
        Thread t5 = new Thread(c, "消费者2");
        Thread t6 = new Thread(c, "消费者3");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();

    }
}

class Baozi04 {
    public static int sum = 0;

}

class Produce04 implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (Baozi04.class) {
                while (Baozi04.sum >= 5) {
                    try {
                        Baozi04.class.wait(); // 等待,释放锁
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Baozi04.sum++;
                System.out.println(Thread.currentThread().getName() + "生产了1个包子,共有包子" + Baozi04.sum);
                Baozi04.class.notify();
            }

        }
    }

}

class Customer04 implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (Baozi04.class) {
                while (Baozi04.sum == 0) {
                    try {
                        Baozi04.class.wait(); // 等待,释放锁
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Baozi04.sum--;
                System.out.println(Thread.currentThread().getName() + "消费了1个包子,还剩" + Baozi04.sum);
                Baozi04.class.notify();
            }

        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值