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; }