当前位置:网站首页>CountDownLatch的用法
CountDownLatch的用法
2022-07-23 05:37:00 【王者之路001】
今日试图解决一个问题,就是在Android中实现多线程同步,但要求几个变量同时同步。
当时,首先想的是,一定得用Android或JAVA的本身机制。
发现有个叫CountDownLatch的机制。
CountDownLatch多线程同步类,可以协调多个线程之间的同步。
CountDownLatch的典型用法如下:
1)创建一个CountDownLatch实例,并确定需要等待的线程或任务数;
2)一个线程或任务完成,CountDownLatch计数器减一;
3)使用CountDownLatch.await(),等CountDownLatch的计数器为0,则运行。
CountDownLatch类里有三个重要的方法
//构造函数,设置引用计数数目
public CountDownLatch(int count){}
//调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public void await() throws InterruptedException { };
//和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };
//将count值减1
public void countDown() { };使用该方法,果然解决了该问题。
附注:
CountDownLatch和CyclicBarrier的区别:
1)CountDownLatch是一个计数器,计数器递减,用完为止;想使用必须重新构造或赋值;
2)CyclicBarrier的计数器像个阀门,到所有线程到达为止,可以进行reset并多次使用。
边栏推荐
- C1--Vivado配置VS Code文本编辑器环境2022-07-21
- Redis source code and design analysis -- 11. Hash object
- Redis源码与设计剖析 -- 11.哈希对象
- Redis源码与设计剖析 -- 8.对象系统
- Database process stuck solution
- [Social Media Marketing] new idea of going to sea: WhatsApp business replaces Facebook
- TS type gymnastics intermediate type gymnastics challenge closing battle
- 部署metersphere
- C语言n番战--链表(九)
- Redis源码与设计剖析 -- 13.有序集合对象
猜你喜欢

简述redis特点及其应用场景

7. Texture mapping

Heidelberg CP2000 circuit board maintenance printer host controller operation and maintenance precautions

Kubernetes technology and Architecture (VI)

Error in na.fail. default(list(Purchase = c(“CH“, “CH“, “CH“, “MM“, “CH“, : missing values in obj

52832Dongle的安装

Cadence (IX) 17.4 rules and spacing settings

Fundamentals of software testing - design method of test cases

An analysis of the CPU explosion of an intelligent transportation background service in.Net

Error in na.fail.default(list(Purchase = c(“CH“, “CH“, “CH“, “MM“, “CH“, : missing values in obj
随机推荐
Redis source code and design analysis -- 13. Ordered collection objects
一次 MySQL 误操作导致的事故,「高可用」都不好使了
Analyse du code source et de la conception de redis - - 7. Liste rapide
The 12th Blue Bridge Cup embedded design and development project
Cadence学习之路(八)PCB放置元器件
Cadence learning path (VIII) PCB placement components
Redis源碼與設計剖析 -- 7.快速列錶
华为高层谈 35 岁危机,程序员如何破年龄之忧?
adb常用命令
Chapter 1 Overview - Section 1 - 1.2 overview of the Internet
[untitled]
Thing JS notes
Understand asp Net core - Cookie based authentication
Filter in MATLAB
QT style syntax definition access, can check the data, can be automatically generated
Error in na.fail.default(list(Purchase = c(“CH“, “CH“, “CH“, “MM“, “CH“, : missing values in obj
LearnOpenGL - Introduction
H1--HDMI接口测试应用2022-07-15
Script of Nacos current limiting query
达人专栏 | 还不会用 Apache Dolphinscheduler?大佬用时一个月写出的最全入门教程