Java多线程-生产者与消费者

来源:互联网 发布:装修花费知乎 编辑:程序博客网 时间:2024/05/21 05:08

Java多线程生产者与消费者,准确说应该是“生产者-消费者-仓储”模型,使用了仓储,使得生产者消费者模型就显得更有说服力。
对于此模型,应该明确一下几点:
1、生产者仅仅在仓储未满时候生产,仓满则停止生产。
2、消费者仅仅在仓储有产品时候才能消费,仓空则等待。
3、当消费者发现仓储没产品可消费时候会通知生产者生产。
4、生产者在生产出可消费产品时候,应该通知等待的消费者去消费。

一、仓库
可以选择有线程安全的PriorityBlockingQueue也可以使用普通的list,为了更加体现多线程这里使用没有线程安全的普通list

private static LinkedList<String> list = new LinkedList<String>();

使用LinkedList是因为删除时更加方便。
二、生产者

/**     * 生产者     *      * @author Administrator     *      */    static class ProductThread implements Runnable {        private int count = 0;        public ProductThread(int count) {            this.count = count;        }        @Override        public void run() {            while(true){                synchronized (list) {                    if(list.size()>20){//容量达到20以上,等待消费                        try {                            list.wait();                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                    }                    for(int i = 1;i<count ;i++){                        System.out.println("生产了一个产品---"+i);                        list.add("str"+i);                    }                    list.notifyAll();                }            }        }    }

三、消费者

static class CustomerThread implements Runnable {        private int count = 0;        public CustomerThread(int count) {            this.count = count;        }        @Override        public void run() {            while(true){                synchronized (list) {                    if(list.size() < count){                        System.out.println("容器中数量不够," + list.size());                        try {                            list.wait();// 等待                        } catch (Exception e) {                            e.printStackTrace();                        }                    }                    for(int i =1;i<=count;i++){                        String remove = list.remove();                        System.out.println("消费掉一个产品--"+remove);                    }                    list.notify();                }            }        }    }

四、测试类

public static void main(String[] args) {        // 每次生产10个        Thread proTh = new Thread(new ProductThread(10));        // 每次消费6个        Thread cusTh = new Thread(new CustomerThread(6));        proTh.start();        cusTh.start();    }

这样一个简单的生产者消费者模型就完成了。

0 0
原创粉丝点击