【JavaSE】多线程中典型的生产者与消费者模型

生产者和消费者模型

  生产者和消费者模式是通过一个容器来解决生产者和消费者之间的强耦合问题,彼此之间不接直接通话,而是通过阻塞队列来进行通话,所以生产者生产完数据不需要等待消费者,直接扔给阻塞队列,消费者不直接找生产者要,直接从阻塞队列里面取,这个阻塞队列就是用来给生产者和消费者解耦的,之前在前面写的工厂模式,模板模式,都是存在第三方

  **下面模拟一个简单的商品生产者和消费者**
//商品类
class Goods {
    //商品名
    private String gooodsName;
    //商品库存
    int count;

    //生产方法
    public synchronized void setGoods(String goodsName) throws InterruptedException {
        while (this.count > 0) {
            wait();
        }
        this.gooodsName = goodsName;
        this.count = count + 1;
        System.out.println("当前线程是: " + Thread.currentThread().getName());
        Thread.sleep(1000);
        System.out.println("生产: " + toString());
        System.out.println("=============================================");
        notifyAll();
    }

    //消费物品
    public synchronized void buyGoods() throws InterruptedException {
        while (0 == this.count) {
            wait();
        }
        this.count = count - 1;
        Thread.sleep(1000);
        System.out.println("当前线程是:" + Thread.currentThread().getName());
        System.out.println("消费: " + toString());
        System.out.println("=============================================");
        notifyAll();
    }

    @Override
    public String toString() {
        return "Goods{" +
                "gooodsName='" + gooodsName + '\'' +
                ", count=" + count +
                '}';
    }
}

//创建生产者和消费者类
class Producer implements Runnable {
    private Goods goods;

    public Producer(Goods goods) {
        this.goods = goods;
    }

    @Override
    public void run() {
        while (true) {
            try {
                this.goods.setGoods("奔驰C200L一辆");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {
    private Goods goods;

    public Consumer(Goods goods) {
        this.goods = goods;
    }

    @Override
    public void run() {
        while (true) {
            try {
                this.goods.buyGoods();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Goods goods = new Goods();
        List<Thread> threadList = new ArrayList<>();
        //10个生产者线程
        for (int i = 0; i < 10; i++) {
            Thread producerThread = new Thread(new Producer(goods));
            producerThread.setName("生产者线程:[" + i + "]");
            threadList.add(producerThread);
        }
        //6个消费线程
        for (int i = 0; i < 6; i++) {
            Thread consumerThread = new Thread(new Consumer(goods));
            consumerThread.setName("消费线程:[" + i + "]");
            threadList.add(consumerThread);
        }
        //启动所有线程
        for (Thread temp : threadList) {
            temp.start();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/eternal_01/article/details/80985355