JUC中提供常用的并发工具类,CountDownLatch、CyclicBarrier、Semaphore。
countdownlatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完毕再执行。从 命名可以解读到countdown是倒数的意思,类似于我们倒计时的概念。
countdownlatch提供了两个方法,一个是countDown,一个是await, countdownlatch初始化的时候需要传入一 个整数,在这个整数倒数到0之前,调用了await方法的程序都必须要等待,然后通过countDown来倒数。
从代码的实现来看,有点类似join的功能,但是比join更加灵活。
共享锁
CountDownLatch类存在一个内部类Sync,是一个同步类,继承了AbstractQueueSynchronizer。
await函数使用当前线程在CountDownLatch倒计时到0之前一直等待。从源码中可以得知await方法会转发到Sync的acquireSharedInterruptibly
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted()) //判断当前线程是否中断
throw new InterruptedException();
if (tryAcquireShared(arg) < 0) //如果倒计时为0返回1,否则返回-1,返回-1时需要阻塞
doAcquireSharedInterruptibly(arg);
}
获取共享锁
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);//创建一个共享模式的锁添加到队列中。
boolean failed = true;
try {
for (;;) {//自选判断当前线程是否为头节点。
final Node p = node.predecessor(); //获取当前节点的前一个节点
if (p == head) {//判断当前线程是头节点
int r = tryAcquireShared(arg); //就判断尝试获取锁
if (r >= 0) { //r>=0表示计数器已经归零了,则释放当前的共享锁。
setHeadAndPropagate(node, r);//是头节点并且倒计时为0,去释放锁。
p.next = null; // help GC
failed = false;
return;
}
}
//当前节点不是头节点,则尝试让当前线程阻塞,第一个方法是判断是否需要阻塞,第二个方法是阻塞。
if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
private void setHeadAndPropagate(Node node, int propagate) {
Node h = head; // Record old head for check below 记录头节点
setHead(node); //设置当前节点为头节点
/*
* Try to signal next queued node if:
* Propagation was indicated by caller,
* or was recorded (as h.waitStatus either before
* or after setHead) by a previous operation
* (note: this uses sign-check of waitStatus because
* PROPAGATE status may transition to SIGNAL.)
* and
* The next node is waiting in shared mode,
* or we don't know, because it appears null
*
* The conservatism in both of these checks may cause
* unnecessary wake-ups, but only when there are multiple
* racing acquires/releases, so most need signals now or soon
* anyway.
*/
//参数propagate传来的1,进入下边代码。
if (propagate > 0 || h == null || h.waitStatus < 0 ||
(h = head) == null || h.waitStatus < 0) {
Node s = node.next;//获得当前节点的下一个节点,如果下一个节点是空表示当前节点为最后一个节 点,或者下一个节点是share节点
if (s == null || s.isShared())
doReleaseShared();//唤醒下一个共享节点
}
}
private void doReleaseShared() {
/*
* Ensure that a release propagates, even if there are other
* in-progress acquires/releases. This proceeds in the usual
* way of trying to unparkSuccessor of head if it needs
* signal. But if it does not, status is set to PROPAGATE to
* ensure that upon release, propagation continues.
* Additionally, we must loop in case a new node is added
* while we are doing this. Also, unlike other uses of
* unparkSuccessor, we need to know if CAS to reset status
* fails, if so rechecking.
*/
for (;;) {
Node h = head;//获得头节点
if (h != null && h != tail) {//如果头节点不为空且不等于tail节点
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {//头节点状态为SIGNAL,
//修改当前头节点的状态为0, 避免下次再进入到这个里面。
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h);//释放后续节点
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
private void unparkSuccessor(Node node) { /* * If status is negative (i.e., possibly needing signal) try * to clear in anticipation of signalling. It is OK if this * fails or if status is changed by waiting thread. */ int ws = node.waitStatus; if (ws < 0) compareAndSetWaitStatus(node, ws, 0);//cas设置状态为0。
/* * Thread to unpark is held in successor, which is normally * just the next node. But if cancelled or apparently null, * traverse backwards from tail to find the actual * non-cancelled successor. */ Node s = node.next; if (s == null || s.waitStatus > 0) { s = null; for (Node t = tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } if (s != null) LockSupport.unpark(s.thread);//唤醒下个节点线程。 }
以共享模式释放锁,并且会调用tryReleaseShared函数,根据判断条件也可能会调用doReleaseShared函数
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {//如果为true,表示计数器已归0了
doReleaseShared();//唤醒处于阻塞的线程
return true;
}
return false;
}
这里主要是对state做原子递减,CountDownLatch的计数器。如果等于0返回true
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
CycliBarrier:一组线程一起执行,每当线程执行到await()方法时,说明此线程已经到达屏障点,当这组线程的最后一个到达屏障点时,再重新notifyALL()唤醒这些线程去执行。此图演示了这一过程。
public CyclicBarrier(int parties) {//参数为屏障拦截的线程数
this(parties, null);
}
public CyclicBarrier(int parties, Runnable barrierAction) {//barrierAction参数为:当所有线程到达屏障点时
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
private int dowait(boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException { final ReentrantLock lock = this.lock; // 锁住 lock.lock(); try { // 当前代//一个线程可以有多个【CyclicBarrier】 final Generation g = generation; // 如果这代损坏了,抛出异常 if (g.broken) throw new BrokenBarrierException();
// 如果线程中断了,抛出异常 if (Thread.interrupted()) { // 将损坏状态设置为 true // 并通知其他阻塞在此栅栏上的线程 breakBarrier(); throw new InterruptedException(); } // 获取下标 int index = --count; // 如果是 0 ,说明到头了 if (index == 0) { // tripped boolean ranAction = false; try { final Runnable command = barrierCommand; // 执行栅栏任务 if (command != null) command.run(); ranAction = true; // 更新一代,将 count 重置,将 generation 重置. // 唤醒之前等待的线程 nextGeneration(); // 结束 return 0; } finally { // 如果执行栅栏任务的时候失败了,就将栅栏失效 if (!ranAction) breakBarrier(); } } for (;;) { try { // 如果没有时间限制,则直接等待,直到被唤醒 if (!timed) trip.await(); // 如果有时间限制,则等待指定时间 else if (nanos > 0L) nanos = trip.awaitNanos(nanos); } catch (InterruptedException ie) { // g == generation >> 当前代 // ! g.broken >>> 没有损坏 if (g == generation && ! g.broken) { // 让栅栏失效 breakBarrier(); throw ie; } else { // 上面条件不满足,说明这个线程不是这代的. // 就不会影响当前这代栅栏执行逻辑.所以,就打个标记就好了 Thread.currentThread().interrupt(); } } // 当有任何一个线程中断了,会调用 breakBarrier 方法. // 就会唤醒其他的线程,其他线程醒来后,也要抛出异常 if (g.broken) throw new BrokenBarrierException(); // g != generation >>> 正常换代了 // 一切正常,返回当前线程所在栅栏的下标 // 如果 g == generation,说明还没有换代,那为什么会醒了? // 因为一个线程可以使用多个栅栏,当别的栅栏唤醒了这个线程,就会走到这里,所以需要判断是否是当前代。 // 正是因为这个原因,才需要 generation 来保证正确。 if (g != generation) return index; // 如果有时间限制,且时间小于等于0,销毁栅栏,并抛出异常 if (timed && nanos <= 0L) { breakBarrier(); throw new TimeoutException(); } } } finally { lock.unlock(); }
}
private void nextGeneration() {
//为唤醒所有处于休眠状态的线程做准备工作
trip.signalAll();
//重置count值为parties
count = parties;
//重置中断状态为false
generation = new Generation();
}
private void breakBarrier() {
//重置中断状态为true
generation.broken = true;
//重置count值为parties
count = parties;
//为唤醒所有处于休眠状态的线程做准备工作
trip.signalAll();
}