生产者消费者问题

package com.zfy.learn;

public class ProductorAndCostumer {
    public static void main(String[] args) {
        Channel channel = new Channel();
        new Thread(
                ()->new Productors(channel).run()
        ).start();
        new Thread(
                ()->new Costumers(channel).run()
        ).start();
    }
}

class Productors implements Runnable{
    Channel channel;

    public Productors(Channel channel) {
        this.channel = channel;
    }

    @Override
    public void run() {
        for (int i = 1; i <100 ; i++) {
            System.out.println("生产编号为"+i+ "的产品");
            try {
                this.channel.produce(new Product(i));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Costumers implements Runnable{
    Channel channel;

    public Costumers(Channel channel) {
        this.channel = channel;
    }

    @Override
    public void run() {
        for (int i = 1; i <100 ; i++) {
            try {
                System.out.println( "消费产品编号:" +this.channel.cost().getId());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Channel{
    Product[] prdts = new Product[10];
    int count =0 ;//计数器

    public synchronized void produce(Product p) throws InterruptedException {
        if(count == prdts.length)
            this.wait();
        prdts[count++] = p;
        this.notifyAll();
    }

    public synchronized Product cost() throws InterruptedException {
        if(count == 0)
            this.wait();
        count--;
        this.notifyAll();
        return prdts[count];
    }


    public Channel() {

    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

class Product{
    int id;

    public Product(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值