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 方法



大致流程如下:图解

=========================================================================================================================================
我只是一粒简单的石子,未曾想掀起惊涛骇浪,也不愿随波逐流
每个人都很渺小,努力做自己,不虚度光阴,做真实的自己,无论是否到达目标点,既然选择了出发,便勇往直前
我不能保证所有的东西都是对的,但都是能力范围内的深思熟虑和反复斟酌

浙公网安备 33010602011771号