源码:

内部类Sync

private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L; //调用AQS类的setState设置状态位
Sync(int count) {
setState(count);
} int getCount() {
return getState();
} protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
} 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;
}
}
}

CountDownLatch初始化

    public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}

可以设置AQS中的state为count

阻塞分析

await

 public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}

acquireSharedInterruptibly

   public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}

具体如下:

1、检测中断标志位

2、调用tryAcquireShared方法来检查AQS标志位state是否等于0,如果state等于0,则说明不需要等待,立即返回,否则进行3

3、调用doAcquireSharedInterruptibly方法进入AQS同步队列进行等待,并不断的自旋检测是否需要唤醒

doAcquireSharedInterruptibly

  private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);//加入队列尾部
boolean failed = true;//是否成功标志
try {
for (;;) {
final Node p = node.predecessor();//前驱
//如果到head的下一个,因为head是拿到资源的线程,此时node被唤醒,很可能是head用完资源来唤醒自己的
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) { //如果大于零,则说明需要唤醒
setHeadAndPropagate(node, r);//将head指向自己,还有剩余资源可以再唤醒之后的线程
p.next = null; // help GC
failed = false;
return;
}
}
//判断状态,寻找安全点,进入waiting状态,等着被unpark()或interrupt()
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}

addWaiter(Node.SHARED),这里将会新增两个node

第一轮循环创建一个new Node(),空节点,线程也为空

第二轮将Node.SHARED加入到队列中,prev指向head

在最后一次release之前,tryAcquireShared会为-1

shouldParkAfterFailedAcquire(Node, Node)

1、源码:
/**
* Checks and updates status for a node that failed to acquire.
* Returns true if thread should block. This is the main signal
* control in all acquire loops. Requires that pred == node.prev.
*
* @param pred node's predecessor holding status
* @param node the node
* @return {@code true} if thread should block
*/
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus; // 获取前驱结点的状态值
if (ws == Node.SIGNAL) // 若前驱结点的状态为SIGNAL状态的话,那么该结点就不要想事了,直接返回true准备休息
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
// 若前驱结点的状态为CANCELLED状态的话,那么就一直向前遍历,直到找到一个不为CANCELLED状态的结点
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
// 剩下的结点状态,则设置其为SIGNAL状态,然后返回false标志等外层循环再次判断
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
} 2、shouldParkAfterFailedAcquire主要是检测前驱结点状态,前驱结点为SIGNAL的话,则新结点可以安安心心休息了;
如果前驱结点大于零,说明前驱结点处于CANCELLED状态,那么则以入参pred前驱为起点,一直往前找,直到找到最近一个正常等待状态的结点;
如果前驱结点小于零,那么就将前驱结点设置为SIGNAL状态,然后返回false依赖acquireQueued的自旋再次判断是否需要进行休息;

第一次进入,ws为0

compareAndSetWaitStatus将pred的waitStatus设置为Node.SIGNAL

第二次进入就直接return true

parkAndCheckInterrupt()

1、源码:
/**
* Convenience method to park and then check if interrupted
*
* @return {@code true} if interrupted
*/
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this); // 阻塞等待
return Thread.interrupted(); // 被唤醒后查看是否有被中断过否?
} 2、parkAndCheckInterrupt首先调用park让线程进入等待状态,然后当park阻塞被唤醒后,再次检测是否曾经被中断过;
而被唤醒有两种情况,一个是利用unpark唤醒,一个是利用interrupt唤醒;

main线程会进入上述代码,阻塞main线程。

释放分析

countDown

    public void countDown() {
sync.releaseShared(1);
} public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}

Sync内部类中的tryReleaseShared

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

可见只有最后一次release的时候才会进入到doReleaseShared

doReleaseShared

    private void doReleaseShared() {
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
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;
}
}

进入上述代码时,head的waitStatus在上述shouldParkAfterFailedAcquire中设置为了Node.SIGNAL

所以这里会调用unparkSuccessor(h)

unparkSuccessor

 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); /*
* 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);
}

这里s=node.next,node为head,s的线程为main线程,这里释放main线程。

流程

参考:

【JUC】JDK1.8源码分析之CountDownLatch(五)

JAVA并发-CountDownLatch的更多相关文章

  1. java 并发——CountDownLatch

    java 并发--CountDownLatch 简介 public class CountDownLatch { private final Sync sync; private static fin ...

  2. java并发--CountDownLatch、CyclicBarrier和Semaphore

    在java 1.5中,提供了一些非常有用的辅助类来帮助我们进行并发编程,比如CountDownLatch,CyclicBarrier和Semaphore,今天我们就来学习一下这三个辅助类的用法. 以下 ...

  3. Java并发--CountDownLatch CyclicBarrier ReentrantLock

    CountDownLatch CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行.CountDownLatch使用一个数字count初始化,使 ...

  4. 【Java并发编程实战】-----“J.U.C”:CountDownlatch

    上篇博文([Java并发编程实战]-----"J.U.C":CyclicBarrier)LZ介绍了CyclicBarrier.CyclicBarrier所描述的是"允许一 ...

  5. Java并发编程:CountDownLatch、CyclicBarrier和Semaphore

    Java并发编程:CountDownLatch.CyclicBarrier和Semaphore 在java 1.5中,提供了一些非常有用的辅助类来帮助我们进行并发编程,比如CountDownLatch ...

  6. Java 并发专题 :闭锁 CountDownLatch 之一家人一起吃个饭

    最近一直整并发这块东西,顺便写点Java并发的例子,给大家做个分享,也强化下自己记忆. 每天起早贪黑的上班,父母每天也要上班,话说今天定了个饭店,一家人一起吃个饭,通知大家下班去饭店集合.假设:3个人 ...

  7. Java并发工具类 - CountDownLatch

    Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...

  8. Java并发编程的4个同步辅助类(CountDownLatch、CyclicBarrier、Semaphore、Phaser)

    我在<JDK1.5引入的concurrent包>中,曾经介绍过CountDownLatch.CyclicBarrier两个类,还给出了CountDownLatch的演示案例.这里再系统总结 ...

  9. 【Java并发核心三】CountDownLatch、CyclicBarrier及Phaser

    个人感觉,看书学习还是需要“不求甚解”,因为一旦太过于计较小的得失,就容易钻牛角尖,学习进度也慢.我们完全可以先学一个大概,等到真正用到的时候再把那些细节丰富起来,就更有针对性. 所以,针对java并 ...

随机推荐

  1. Semantic 3D

    Semantic 3D 这个数据级别的训练集有一个小BUG,是这个neugasse_station1_xyz_intensity_rgb.7z, 解压之后的名字是station1_xyz_intens ...

  2. Eclipse中如何安装Git插件

    现在的Eclipse一般都自带Git插件. 检查Eclipse是否有Git插件: 方法一:Help—>About Eclipse,出现下面的图标,说明Eclipse中已有Git插件,就不用安装了 ...

  3. 用 FFLIB 实现 Apex 企业设计模式

    Apex 企业设计模式将应用分为服务层.模型层.选择逻辑层.工作单元几个部分.FFLIB 是一个开源的 Apex 框架,可以帮助开发者快速建立相关的功能. FFLIB 的安装 FFLIB 可以直接部署 ...

  4. 【洛谷4045】[JSOI2009] 密码(状压+AC自动机上DP)

    点此看题面 大致题意: 给你\(n\)个字符串,问你有多少个长度为\(L\)的字符串,使得这些字符串都是它的子串.若个数不大于\(42\),按字典序输出所有方案. 状压 显然,由于\(n\)很小,我们 ...

  5. Kavex GameDev-Resources

    https://github.com/Kavex/GameDev-Resources 各种资源

  6. 01 学习数据分析的python库

    网页爬取 1.requests 2.BeautifulSoup 3.Scrapy 科学计算与数据分析 1.scipy 2.numpy 3.pandas 机器学习和深度学习 1.Scikit-learn ...

  7. H5开发 连接蓝牙打印机 打印标签(斑马ZR628)

    1.连接蓝牙打印机(先用手机自带蓝牙进行配对),然后绑定出已配对的蓝牙设备(用来选择/切换打印机之用),代码如下 已配对蓝牙设备,中显示的就是已连接的,点击一下即可 代码: <!DOCTYPE ...

  8. 物联网架构成长之路(32)-SpringBoot集成MQTT客户端

    一.前言 这里虽然是说MQTT客户端.其实对于服务器来说,这里的一个具有超级权限的MQTT客户端,就可以做很多事情.比如手机APP或者网页或者第三方服务需要发送数据到设备,但是这些又不是设备,又不能让 ...

  9. npm和yarn的区别,我们该如何选择?

    首先,这两个都属于js包管理工具,都可以安装包或者模块yarn 是由facebook.google等联合开发推出的区别: npm 下载包的话 比如npm install它是按照包的排序,也就是队列挨个 ...

  10. 3、Ext.NET 1.7 官方示例笔记-表单

    表单[Form],就是向客户收集资料的窗口,用户在表单填写好各种信息,然后提交到服务器,服务器接收并保存到数据库里. 表单的字段类型很多,我们从最简单的开始吧. 1.1 .先开始组合框吧(ComboB ...