简单的消费者和生产者

在一段代码里使用了ExecutorService

ExecutorService executorService = Executors.newFixedThreadPool(5);

直接用Executors工厂获得一个线程池,队列策略为LinkedBlockingQueue。
但是这样就存在一个问题,当有很多很多任务需要处理的时候,队列就被撑的很大,搞不好就内存溢出了。
于是就写了下面这个类,来保证最多只有100个任务被建立。在调用executorService.execute()之前,都进行一次消费,线程执行完之后,进行一次生产。

    class SyncControl {
        private int index = 100;

        private int size  = 100;

        public SyncControl(int size) {
            if (logger.isInfoEnabled()) {
                logger.info("消费队列被建立:size=" + size);
            }
            Assert.isTrue(size > 0);
            this.size = size;
            this.index = this.size;

        }

        /**
         * 生产
         */
        public synchronized void pruduce() {
            while (this.index >= this.size) {
                if (logger.isDebugEnabled()) {
                    logger.debug("当前队列已满");
                }

                try {
                    this.wait();
                } catch (InterruptedException e) {
                    //不需要logger异常
                }
            }
            this.index++;
            if (logger.isDebugEnabled()) {
                logger.debug("生产成功,当前index:" + index);
            }

            this.notifyAll();
        }

        /**
         * 消费
         */
        public synchronized void consume() {
            while (this.index <= 0) {
                if (logger.isDebugEnabled()) {
                    logger.debug("没有可消费的产品");
                }
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    //不需要logger异常
                }
            }

            this.index--;
            if (logger.isDebugEnabled()) {
                logger.debug("消费成功,当前index:" + index);
            }
            this.notifyAll();
        }
    }
, , ,

Leave a Reply