java多线程经典问题三--生产者消费者问题

版权声明:欢迎转载,注明出处 https://blog.csdn.net/jklcl/article/details/81710086

单生产者单消费者:
两个线程:生产线程,消费线程
两个任务:生产任务,消费任务
共享一份数据

public class Demo4 {
    public static void main(String[] args) {
        //1.准备数据
        Product product = new Product();
        //2.创建生产消费任务
        Produce produce = new Produce(product);
        Consume consume = new Consume(product);
        //3.创建生产线程
        Thread thread1 = new Thread(produce);
        Thread thread2 = new Thread(consume);
        //4.开启线程
        thread1.start();
        thread2.start();
    }
}

//数据类
class Product{
    String name;
    double price;
    int count=0;

    //标识
    boolean flag = false;

    //准备生产
    public synchronized void setProduce(String name, double price) {
         if(flag == true) {
             try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
         }
         this.name = name;
         this.price = price;
         count ++;
         System.out.println(Thread.currentThread().getName()+"生产了:" + name+"  产品数量:"+count+"  价格"+price);
         flag = !flag;
         notify();
    }
    //准备消费
    public synchronized void getProduce() {
        if(flag == false) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"消费了:" + name+"  产品数量:"+count+"  价格"+price);
        flag = !flag;
        notify();
    }
}
//生产任务
class  Produce implements Runnable{

    Product product;

    public Produce(Product product) {
        super();
        this.product = product;
    }

    @Override
    public void run() {
        while(true) {
            product.setProduce("bingbing", 10);
        }
    }
}

//消费任务
class  Consume implements Runnable{
    Product product;

    public Consume(Product product) {
        super();
        this.product = product;
    }


    @Override
    public void run() {
        while(true) {
            product.getProduce();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/jklcl/article/details/81710086