美文网首页Java并发编程学习笔记
《JAVA程序性能优化》-ArrayBlockingQueue的

《JAVA程序性能优化》-ArrayBlockingQueue的

作者: 熊熊要更努力 | 来源:发表于2019-07-18 09:42 被阅读0次
    /**
     * @author shujun.xiong
     * @date 2019/7/18 9:32
     */
    
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class ConditionTest {
        private final Integer[] items;
        private final ReentrantLock lock;
        private final Condition notEmpty;
        private final Condition notFull;
        private int putIndex, takeIndex, count;
    
        public ConditionTest() {
            this.items = new Integer[Integer.MAX_VALUE];
            lock = new ReentrantLock(true);
            this.notEmpty = lock.newCondition();
            this.notFull = lock.newCondition();
            putIndex = 0;
            takeIndex = 0;
            count = 0;
        }
    
        public void put(Integer number) throws InterruptedException {
            if (number == null) {
                throw new NullPointerException();
            }
            final Integer[] items = this.items;
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                try {
                    while (count == items.length) {
                        notFull.await();
                    }
                } catch (InterruptedException e) {
                    notFull.signal();
                    throw e;
                }
    
                insert(number);
            } finally {
                lock.unlock();
            }
            
        }
    
        private void insert(Integer e) {
            items[putIndex] = e;
            putIndex++;
            ++count;
            notEmpty.signal();
        }
    
        public Integer take() throws InterruptedException {
            final ReentrantLock lock = this.lock;
            lock.lockInterruptibly();
            try {
                try {
                    while (count == 0) {
                        notEmpty.await();
                    }
                } catch (InterruptedException e) {
                    notEmpty.signal();
                    throw e;
                }
                Integer x = extract();
                return x;
            } finally {
                lock.unlock();
            }
        }
    
        private Integer extract() {
            final Integer[] items = this.items;
            Integer x = items[takeIndex];
            takeIndex++;
            --count;
            notFull.signal();
            return x;
        }
    }
    

    相关文章

      网友评论

        本文标题:《JAVA程序性能优化》-ArrayBlockingQueue的

        本文链接:https://www.haomeiwen.com/subject/xerklctx.html