生产者与消费者(JAVA)

生产者与消费者

先有一个容器,生产者只对容器中添加产品,消费者只对容器中消费产品。

当生产者检测到容器已满,就会进入wait状态,如果未满,则notifyAll来唤醒消费者线程。

当消费者线程检测到容器为空时,进入wait状态,如果不是,则消费,同时nitifyAll。

public class PandC {
    public static void main(String[] args) {
        Container container = new Container();
        new Producer(container).start();
        new Consumer(container).start();
    }
}
//生产者
class Producer extends Thread{
    Container container;
    Producer(Container container){
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("生产了第"+i+"个产品");
            container.push(new Product(i));
        }
    }
}
//消费者
class  Consumer extends Thread{
    Container container;
    Consumer(Container container){
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了第"+container.pop().id+"个产品");
        }
    }
}
//产品
class Product{
    int id;
    Product(int id){
        this.id = id;
    }
}
//容器
class Container{
    //容器大小
    Product[] products = new Product[10];
    //计数
    int count = 0;
    public synchronized void push(Product product){
        //如果容器已满,则生产者等待,消费者消费
        if(count==products.length){
            try {
                this.wait(); //wait和sleep的不同之处在于,wait会释放锁
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        products[count] = product;
        count++;
        //通知消费者消费
        this.notifyAll(); //唤醒其他所有线程
    }
    public synchronized Product pop(){
        //如果没有产品了,等待生产者生产
        if(count==0){
            try {
                this.wait();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        count--;

        Product product = products[count];
        this.notifyAll();
        return product;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值