当前位置:网站首页>AQS之countDownLatch源码分析
AQS之countDownLatch源码分析
2022-07-28 05:27:00 【yfyh2021】
- 介绍
CountDownLatch(闭锁)是一个同步协助类,允许一个或多个线程等待,直到其他线程完成操作集。
- 代码准备
- 让多个线程等待一个线程执行
public class CountDownLatchTest1 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
for(int i=0;i<5;i++){
new Thread(()->{
try {
countDownLatch.await();
String parter = "【" + Thread.currentThread().getName() + "】";
System.out.println(parter + "开始执行……");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
Thread.sleep(2000);
System.out.println("等待");
countDownLatch.countDown();
}
}
- 让一个线程等待多个线程执行
public class CountDownLatchTest2 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
for(int i=0;i<5;i++){
final int index =i;
new Thread(()->{
try {
Thread.sleep(1000 +
ThreadLocalRandom.current().nextInt(1000));
System.out.println(Thread.currentThread().getName()
+ " finish task" + index);
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
System.out.println("主线程等待");
countDownLatch.await();
System.out.println("主线程:在所有任务运行完成后,进行结果汇总");
}
}

- 源码分析

进入await()方法发现acquireSharedInterruptibly()方法是传入固定参数1。

又是AQS这块熟悉的代码,先是try尝试,然后是do进行一些列入队和阻塞操作。从这个方法我们可以看到countDownLatch是共享锁。

闭锁的try方法相当简单,其state为我们创建闭锁时传入的值。返回-1,进入我们AQS的doAcquireSharedInterruptibly()方法中进行入队和阻塞。

闭锁的countDown()方法也是我们常见到的releaseShared,且固定传1

其中doReleaseShared()方法为AQS共用的解锁方法,可参考semaphore。我们需要看一下tryReleaseShared()方法在countDownLatch中是如何实现的。

可见每次闭锁每次countdown就会将state减一,当state为0时就会唤醒线程。
- 总结
- 我们可以看到在reentrantlock中state属性为重入次数,但是在semaphore中可以理解为资源量,在countDownLatch中可以理解为计数器可知道。独占锁是可以重入的,而共享锁是不支持重入的。
- 我们看到countDownLatch作用比较类似join()方法。但是闭锁相对于join来说会更灵活,它既可以在n个线程里进行countDown操作,也可以在一个线程里进行n此countDown操作。而join的实现原理是不停的检查join的线程是否存活,如果join线程存活则会让当前线程永远等待。
边栏推荐
猜你喜欢

江中ACM新生10月26日习题题解

2022-06-07 VI. log implementation

气传导蓝牙耳机什么牌子好、气传导耳机最好的品牌推荐

QT batch operation control and set signal slot

What are the open earphones? Four types of air conduction earphones with excellent sound quality are recommended

Bug experience related to IAP jump of stm32

微信小程序自定义编译模式

如何模拟实现strcpy库函数

valgrind工具

Hugging face's problem record I
随机推荐
JSP should pass parameters to the background while realizing the file upload function
刷题记录----哈希表
【实现简易版扫雷小游戏】
Leetcode 刷题日记 剑指 Offer II 048. 序列化与反序列化二叉树
OJ 1020 minimum palindromes
2021-11-10
MFC uses the console to print program information
Pyppeter drop-down selenium drop-down
C语言的文件操作
What's a good gift for your girlfriend on Chinese Valentine's day? Boys who can't give gifts, look!
ubuntu mysql 设置远程访问权限
OJ 1451 digital games
gerapy 使用
Solve the problem that the memory occupation is higher than that of the application process
SSAO By Computer Shader(一)
[c语言]简易通讯录的实现
set_ multicycle_ path
Pyppeteer 被识别 绕过检测
C语言memcpy库函数与memmove的作用
关于Shader KeyWord的整理