From 7fc5004c9f72e3c6cd73db1dede2e254119df84d Mon Sep 17 00:00:00 2001 From: OSrange <2462206872@qq.com> Date: Sat, 15 Jul 2023 17:28:24 +0800 Subject: [PATCH] Update java-concurrent-questions-03.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 前面都说了await()是阻塞了,线程不是cas自旋等待state为0,而是阻塞依赖任务线程调用releaseShared()来唤醒,只有当最后一个线程releaseShared()使state为0,再唤醒主线程,主线程检测到state为0,才会从await()返回。以下为测试源码: 运行案例与源码分析:https://blog.csdn.net/m0_56602092/article/details/131740816 --- docs/java/concurrent/java-concurrent-questions-03.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/java/concurrent/java-concurrent-questions-03.md b/docs/java/concurrent/java-concurrent-questions-03.md index 8185520e..5f189376 100644 --- a/docs/java/concurrent/java-concurrent-questions-03.md +++ b/docs/java/concurrent/java-concurrent-questions-03.md @@ -728,7 +728,7 @@ public final boolean releaseShared(int arg) { ### CountDownLatch 的原理是什么? -`CountDownLatch` 是共享锁的一种实现,它默认构造 AQS 的 `state` 值为 `count`。当线程使用 `countDown()` 方法时,其实使用了`tryReleaseShared`方法以 CAS 的操作来减少 `state`,直至 `state` 为 0 。当调用 `await()` 方法的时候,如果 `state` 不为 0,那就证明任务还没有执行完毕,`await()` 方法就会一直阻塞,也就是说 `await()` 方法之后的语句不会被执行。然后,`CountDownLatch` 会自旋 CAS 判断 `state == 0`,如果 `state == 0` 的话,就会释放所有等待的线程,`await()` 方法之后的语句得到执行。 +`CountDownLatch` 是共享锁的一种实现,它默认构造 AQS 的 `state` 值为 `count`。当线程使用 `countDown()` 方法时,其实使用了`tryReleaseShared`方法以 CAS 的操作来减少 `state`,直至 `state` 为 0 。当调用 `await()` 方法的时候,如果 `state` 不为 0,那就证明任务还没有执行完毕,`await()` 方法就会一直阻塞,也就是说 `await()` 方法之后的语句不会被执行。直到`count` 个线程调用了`countDown()`使state值被减为0,或者调用`await()`的线程被中断,该线程才会从阻塞中被唤醒,`await()` 方法之后的语句得到执行。 ### 用过 CountDownLatch 么?什么场景下用的?