Condition应用和源码分析

1.Condition实现队列
public class LockQueue<T> {

    private Object[] queue;
    private ReentrantLock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();
    private int putIndex;
    private int takeIndex;
    private int count;
    public LockQueue(int count) {
        queue = new Object[count];
    }
    public void put(T t) throws InterruptedException {
        lock.lock();
        try {
            while (count == queue.length) {
                notFull.await();
            }
            queue[putIndex] = t;
            System.out.println("put:"+t);
            putIndex++;
            if(putIndex == queue.length ){
                putIndex = 0;
            }
            count++;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public T take() throws InterruptedException {
        lock.lock();
        try {
            while (0 ==  count) {
                notEmpty.await();
            }
            Object o = queue[takeIndex];
            System.out.println("take:"+o);
            queue[takeIndex] = null;
            takeIndex++;
            if(takeIndex == queue.length ){
                takeIndex = 0;
            }
            count--;
            notFull.signal();
            return (T)o;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        LockQueue lockQueue = new LockQueue(5);
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    lockQueue.put(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    lockQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

2.Condition源码分析

    lock.newCondition() 实际返回ConditionObject

      signal 方法

 

 

 

 

     大致流程如下:图解

 

posted @ 2019-03-03 22:16  Don'tYouSee  阅读(137)  评论(0)    收藏  举报