void await() throws InterruptedException
|
进入等待,直到被通知或中断
|
void awaitUninterruptibly()
|
进入等待,直到被通知,不响应中断
|
long awaitNanos(long nanosTimeout) throws InterruptedException
|
等待xxx纳秒
|
boolean awaitUntil(Date deadline) throws InterruptedException
|
等待,直到某个时间点
|
void signal()
|
唤醒
|
void signalAll()
|
唤醒全部等待在condition上的线程,会从等待队列挨个signal()
|
public class BoundedQueue<T> { private Object[] items; //添加的下标,删除的下标和数组当前数量 private int addIndex, removeIndex, count; private Lock lock = new ReentrantLock(); private Condition empty = lock.newCondition(); private Condition full = lock.newCondition(); //构造方法 public BoundedQueue(int size){ items = new Object[size]; } //添加元素,若是数组满,则添加线程进入等待,直到有空位 public void add(T t) throws InterruptedException{ lock.lock(); try { while (count == items.length) //改为if会如何 full.await(); items[addIndex] = t; if(++addIndex == items.length) addIndex = 0; ++count; empty.signal(); }finally { lock.unlock(); } } //从头部删除一个元素,若是数组空,则删除线程进入等待状态,直到添加新元素 public T remove() throws InterruptedException{ lock.lock(); try{ while (count == 0) empty.await(); Object x = items[removeIndex]; if(++removeIndex == items.length) removeIndex = 0; --count; full.signal(); return (T)x; }finally { lock.unlock(); } } }
public final void await() throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); //当前线程加入等待队列 int savedState = fullyRelease(node); //释放同步状态,也就是释放锁 int interruptMode = 0; while (!isOnSyncQueue(node)) { LockSupport.park(this); if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) break; } if (acquireQueued(node, savedState) && interruptMode != THROW_IE) interruptMode = REINTERRUPT; if (node.nextWaiter != null) // clean up if cancelled unlinkCancelledWaiters(); if (interruptMode != 0) reportInterruptAfterWait(interruptMode); }
public final void signal() { if (!isHeldExclusively()) //是否获取了锁(重入锁中是直接 return 独占锁线程==当前线程) throw new IllegalMonitorStateException(); Node first = firstWaiter; //等待队列头节点 if (first != null) doSignal(first); } private void doSignal(Node first) { do { if ( (firstWaiter = first.nextWaiter) == null) //等待队列首节点的后继节点为空,说明只有一个节点,那么尾节点也置空 lastWaiter = null; first.nextWaiter = null; } while (!transferForSignal(first) && (first = firstWaiter) != null); // 等待队列首节点唤醒失败,则唤醒下个节点 } final boolean transferForSignal(Node node) {// 将节点加入同步队列 if (!compareAndSetWaitStatus(node, Node.CONDITION, 0)) // 设置节点状态为0----(等待队列状态只能为-2,-3,用-2进行cas设置失败,说明是-3) return false; Node p = enq(node); // 放入同步队列尾部 int ws = p.waitStatus; if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)) LockSupport.unpark(node.thread); return true; }