码迷,mamicode.com
首页 > 其他好文 > 详细

生产者与消费者模式

时间:2018-05-10 17:09:53      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:his   zed   仓储   current   ide   信息   ring   main   static   

生产者与消费者模式就是解耦生产者与消费者的模式,通过例如商品来建立他们之间的联系,生产者只要生产商品就行,消费者只要消费商品。常用于并发,生产者线程生产商品,消费者消费商品,通过消费信息进行通讯。

用object的wait与notify实现

//商品
public class Product {
    private int productTotal = 0;

    private int maxFruit = 10;

    public synchronized void produce() {
        this.productTotal++;
        if (productTotal > 0) {
            this.notifyAll();
            System.out.println(Thread.currentThread().getName() + "生产了一个商品,现仓储量:" + productTotal);
        }
        if (maxFruit == 10) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void consume() {
        if (productTotal == 0) {
            if (productTotal <= maxFruit) {
                this.notifyAll();
            }
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            this.productTotal--;
            System.out.println(Thread.currentThread().getName() + "消费了一个商品,现仓储量:" + productTotal);
        }
    }
}
//生产者
public class Producer implements Runnable {
    private Product fruitShop;

    public Producer(Product fruitShop) {
        this.fruitShop = fruitShop;
    }

    @Override
    public void run() {
        while (true) {
            fruitShop.produce();
        }
    }
}
//消费者
public class Consumer implements Runnable {

    private Product fruitShop;

    public Consumer(Product fruitShop) {
        this.fruitShop = fruitShop;
    }

    @Override
    public void run() {
        while (true) {
            fruitShop.consume();
        }
    }

}
public class TestLock5 {

    public static void main(String[] args) {
        Product fruitShop = new Product();
        Producer producer = new Producer(fruitShop);
        Consumer consumer = new Consumer(fruitShop);
        Thread thread1 = new Thread(producer, "生产者");
        Thread thread2 = new Thread(consumer, "消费者");
        thread1.start();
        thread2.start();
        try {
            thread2.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

生产者与消费者模式

标签:his   zed   仓储   current   ide   信息   ring   main   static   

原文地址:https://www.cnblogs.com/thomas-seven/p/9019966.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!