生产者与消费者问题----多线程通信


```java
/*
 * 生产者与消费者例题
 *
 * */

class Product {
    int numOfProduct = 0;
    //生产产品
    public synchronized void addProdect() throws InterruptedException {//同步监视器:Product的对象,下方main方法中的p
        if(this.numOfProduct<20){
            this.numOfProduct++;
            System.out.println("生产者开始生产第"+this.numOfProduct+"个产品");
            //this.numOfProduct++;
            notify();
        }else{
            //等待
            wait();
        }
    }
    //消费产品
    public synchronized void subProdect() throws InterruptedException {//同步监视器:Product的对象,下方main方法中的p
        if(this.numOfProduct>0){
           // System.out.println("消费者开始生产产品");
            System.out.println("消费者开始消费第"+this.numOfProduct+"个产品");
            this.numOfProduct--;
            notify();
        }else{
            //等待
            wait();
        }
    }
}

class Productor implements Runnable {
    private Product p;

    public Productor(Product p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
               // System.out.println("生产者开始生产产品");
                p.addProdect();//生产更多的产品
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //System.out.println("生产产品:现有产品数:" + p.numOfProduct);
        }
    }
}
class Customerw implements Runnable{
    private Product p;

    public Customerw(Product p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                //System.out.println("消费者开始消费产品");
                p.subProdect();//消费产品
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //System.out.println("消费产品:现有产品数:" + p.numOfProduct);
        }
    }
}

public class Exchange {
    public static void main(String[] args)  {
        Product p=new Product();
        Customerw c=new Customerw(p);
        Productor pro=new Productor(p);

        Thread t1=new Thread(c);
        Thread t2=new Thread(pro);
        t1.start();
        t2.start();

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值