当前位置:网站首页>Detailed explanation of tool classes countdownlatch and cyclicbarrier of concurrent programming learning notes
Detailed explanation of tool classes countdownlatch and cyclicbarrier of concurrent programming learning notes
2022-07-29 05:57:00 【People with different feelings】
1、CountDownLatch Usage details
Concept
CountDownLatch Class allows one or more threads to wait for other threads to complete operations .CountDownLatch Receive a int Type parameter , Indicates the number of worker threads to wait , After each subtask is completed, use countDown Method to subtract 1 operation , Waiting for thread usage await Method to wait , Until all subtasks are completed , The waiting thread will be called to execute .
Example
Create child threads , Simulation execution task , When the subtask is completed , The main thread is awakened to continue execution , The specific implementation is as follows :
public static void main(String[] args) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(5);
for(int i=0;i<5;i++){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
// Simulation tasks are time-consuming
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + " The thread executes the task !");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
// Counter count down, Thread execution complete
latch.countDown();
}
}
});
t.start();
}
// Make the current thread enter the synchronization queue to wait , until latch The value of is reduced to 0 Or the current thread is interrupted , The current thread will be awakened .
latch.await();
System.out.println(" All subtasks have been completed !");
}
Be careful :
1、 structure CountDownLatch The integer of the object corresponds to the subtask one by one , If the value is greater than latch.countDown() Number of executions , The main thread will be waiting , If it is less than latch.countDown() Carry out this , The main thread will be awakened in advance .
2、 To guarantee latch.countDown() Method execution , Generally put it in finally Block of code , Ensure that it can also be executed under abnormal circumstances , Avoid the main thread waiting indefinitely .
CountDownLatch Common methods
1、Sync Inner class
CountDownLatch Through inner class Sync To achieve synchronous semantics , and Sync Inherit AQS(AbstractQueuedSynchronizer). The specific implementation is as follows :
// Definition Sync Variable , for CountDownLatch Method use in
private final Sync sync;
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
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;
}
}
}
2、 Constructors
The parameter cannot be less than 0 Positive integer of , Identification counter .
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
3、await() Method
CountDownLatch There are two constructors , A no arguments , A parameter with expiration time . The specific implementation is based on AQS Of acquireSharedInterruptibly() and tryAcquireSharedNanos() Method to complete .
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
//AbstractQueuedSynchronizer Class
public final void acquireSharedInterruptibly(int arg) throws InterruptedException {
// If interrupted , Throw an exception
if (Thread.interrupted())
throw new InterruptedException();
// Try to get synchronization status
if (tryAcquireShared(arg) < 0)
// Failed to get synchronization status , The spin
doAcquireSharedInterruptibly(arg);
}
// stay CountDownLatch Of Sync Rewriting in , Said when count==0 when , To be successful
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquireShared(arg) >= 0 ||
doAcquireSharedNanos(arg, nanosTimeout);
}
4、countDown() Method
send latch The value of the reduction 1, If it's down to 0, Will wake up all waiting in this latch On the thread .
public void countDown() {
sync.releaseShared(1);
}
5、getCount() Method
get latch The numerical .
public long getCount() {
return sync.getCount();
}
2、CyclicBarrier Usage details
CyclicBarrier( Circulation barrier ), and CountDownLatch similar , It is also a synchronization assistant tool , It allows multiple threads to wait for each other to reach a barrier after performing corresponding operations (barrier point).CyclicBarrier It is also very suitable for a serial task to be divided into several parallel sub tasks , When all subtasks are finished, continue the next work .
CyclicBarrier Also receive a int The parameters of type , But and CountDownLatch The parameter meaning of is different , Here is the number of threads intercepted by the barrier ( Fragmentation ). and CountDownLatch comparison ,CyclicBarrier Can be reused , and CountDownLatch When the counter is 0 Can't be used again .
meanwhile CyclicBarrier Another constructor is also provided CyclicBarrier(int parties, Runnable barrierAction) , among barrierAction It can be used when all threads reach the barrier , Priority operations , Then wake up all threads .
Example
In accordance with the above CountDownLatch Example , We use CyclicBarrier Also realize , as follows :
public class CyclicBarrierTest {
public static void main(String[] args) throws InterruptedException {
final CyclicBarrier barrier = new CyclicBarrier(5);
List<Thread> list = new ArrayList<>();
for(int i=0;i<5;i++){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
// Simulation tasks are time-consuming
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + " The thread executes the task !");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
try {
// Wait here for other sub threads to arrive barrier point
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
});
list.add(t);
t.start();
}
list.forEach(t ->{
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(" All subtasks have been completed !");
}
}
and CountDownLatch comparison , Construction tool objects are similar , But after the execution of the sub thread is completed , So this is calling theta barrier.await() Method , The main thread is borrowed List Collection and sub thread join() Method realization , It seems not as good as CountDownLatch Intuitive and easy to use . Actually , This is because the design ideas of the two tool classes are different :CountDownLatch Use counter , When the counter is 0 when , Wake up other threads ; and CyclicBarrier Is to use a barrier , When all threads reach the barrier , Start to work . So realize the above example , A more elegant way , We also regard the main thread as one of them , So constructed CyclicBarrier Object time , Parameters +1, Then the main thread also uses await() The method can , The implementation is as follows :
public class CyclicBarrierTest {
public static void main(String[] args) throws InterruptedException {
final CyclicBarrier barrier = new CyclicBarrier(6);
for(int i=0;i<5;i++){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
// Simulation tasks are time-consuming
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + " The thread executes the task !");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
try {
// Wait here for other sub threads to arrive barrier point
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
try {
barrier.await();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(" All subtasks have been completed !");
}
}
In addition to the above differences ,CyclicBarrier It can also be reused , Here we simulate the scene of students' class , To get to know CyclicBarrier Reusable usage .
- Before the beginning of each class , Start roll call , Simulate five students
- Each thread represents a student , Be ready , Prepare for class
- After the roll call , The teacher began his class
- At the end of the course , Recess activities
- Go on to the next lesson
public class CyclicBarrier2Test {
public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
final CyclicBarrier barrier = new CyclicBarrier(6, new Runnable() {
@Override
public void run() {
System.out.println(" Roll call complete , Start class !");
}
});
dianMing(" Chinese language and literature ",barrier);
barrier.await();
System.out.println(" The Chinese class is over , Student recess activities !");
dianMing(" mathematics ",barrier);
barrier.await();
System.out.println(" Math class is over , Student recess activities !");
}
/** * Simulate class roll call * @param type * @param barrier */
public static void dianMing(String type, CyclicBarrier barrier){
System.out.println(" Current course :" + type + ", Prepare for class , Start roll call :");
int count = 5;//5 A student
for(int i=0;i<count;i++){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
// Simulation tasks are time-consuming
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + " Children's shoes , Ready , Waiting for class !");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
try {
// Wait here for other sub threads to arrive barrier point
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
}
}
The output is as follows :
Current course : Chinese language and literature , Prepare for class , Start roll call :
Thread-3 Children's shoes , Ready , Waiting for class !
Thread-1 Children's shoes , Ready , Waiting for class !
Thread-4 Children's shoes , Ready , Waiting for class !
Thread-2 Children's shoes , Ready , Waiting for class !
Thread-0 Children's shoes , Ready , Waiting for class !
Roll call complete , Start class !
The Chinese class is over , Student recess activities !
Current course : mathematics , Prepare for class , Start roll call :
Thread-6 Children's shoes , Ready , Waiting for class !
Thread-7 Children's shoes , Ready , Waiting for class !
Thread-5 Children's shoes , Ready , Waiting for class !
Thread-8 Children's shoes , Ready , Waiting for class !
Thread-9 Children's shoes , Ready , Waiting for class !
Roll call complete , Start class !
Math class is over , Student recess activities !
CyclicBarrier Common methods
1、 Constructors
CyclicBarrier It includes two constructors , In the previous example , We all use .
- CyclicBarrier(int parties) Constructors : structure CyclicBarrier And passed in parties, among parties Indicates the number of threads that need to reach the barrier , The number of threads reaching the barrier is equal to parties when , Will continue to execute subsequent code .
- CyclicBarrier(int parties, Runnable barrierAction) Constructors : structure CyclicBarrier It's not just coming in parties, And specify a Runnable Interface , When all threads arrive barrier point When , The Runnable The interface will be called , Sometimes we need to perform an action after all tasks are completed , You can use this CyclicBarrier The construction method of .
2、int getParties() Method
obtain CyclicBarrier At the time of construction parties, This value once CyclicBarrier Creation will not be changed .
3、await() Method
CyclicBarrier There are two await Overloading methods , as follows :
await() Method one of the methods we use most , After calling the method , The current thread will enter the blocking state , Waiting for other threads to execute await() Methods into the barrier point, And then all exit the blocking state , When CyclicBarrier Inside count by 0 when , call await() The method will return directly without entering the blocking state .
await(long timeout, TimeUnit unit) Method : This method is similar to parameterless await The method is similar to , It just adds the function of timeout , When other threads do not arrive within the set time barrier point when , The current thread will also exit the blocking state .
4、isBroken()
return barrier Of broken state , A thread due to execution await Method to enter the blocking state , If the thread is interrupted , that isBroken() The method will return true.
- When a thread is executing CyclicBarrier Of await Method to enter the blocking state , At this time, performing an interrupt operation on this thread will cause CyclicBarrier By broken.
- By broken Of CyclicBarrier At this time, it can no longer be used directly , If you want to use it, you must use reset Method to reset it .
- If there are other threads executing at this time await Method to enter the blocking state , Then the thread will be awakened and thrown BrokenBarrierException abnormal .
5、getNumberWaiting() Method
This method returns the current barrier How many threads have executed await Method instead of how many threads have not arrived barrier point.
6、reset() Method
The main function is to interrupt the current barrier, And regenerate a generation, And will barrier Internal counters count Set to parties value , But here's the thing , If there is still no arrival barrier point The thread of , Then all threads will be interrupted and exit blocking , here isBroken() Method will return false instead of true.
3、CyclicBarrier And CountDownLatch Different
- CoundDownLatch Of await Method will wait for the counter to be count down To 0, And perform CyclicBarrier Of await The thread of the method will wait for other threads to arrive barrier point.
- CyclicBarrier Internal counters count It can be reset , Thus making CyclicBarrier Can also be reused , and CoundDownLatch Can not .
- CyclicBarrier By Lock and Condition Realized , and CountDownLatch The synchronization controller AQS(AbstractQueuedSynchronizer) To achieve .
- In the structure CyclicBarrier Not allowed in case of emergency parties by 0, and CountDownLatch allows count by 0.
边栏推荐
- 手撕ORM 框架(泛型+注解+反射)
- Study and research the way of programming
- Training log 7 of the project "construction of Shandong University mobile Internet development technology teaching website"
- Super simple integration HMS ml kit face detection to achieve cute stickers
- 突破硬件瓶颈(一):Intel体系架构的发展与瓶颈挖掘
- Get the number of daffodils
- 中海油集团,桌面云&网盘存储系统应用案例
- 华为2020校招笔试编程题 看这篇就够了(上)
- Markdown语法
- Dao race track is booming. What are the advantages of m-dao?
猜你喜欢

量化开发必掌握的30个知识点【什么是分笔逐笔数据】?

主流实时流处理计算框架Flink初体验。

Madonna "hellent" bought $1.3 million NFT boring ape, which is now considered too expensive

一文读懂Move2Earn项目——MOVE

Some opportunities for young people in rural brand building

Huawei 2020 school recruitment written test programming questions read this article is enough (Part 1)

Breaking through the hardware bottleneck (I): the development of Intel Architecture and bottleneck mining

识变!应变!求变!

Super simple integration HMS ml kit face detection to achieve cute stickers

Xsan is highly available - xdfs and San are integrated with new vitality
随机推荐
Machine learning makes character recognition easier: kotlin+mvvm+ Huawei ml Kit
通过简单的脚本在Linux环境实现Mysql数据库的定时备份(Mysqldump命令备份)
Huawei 2020 school recruitment written test programming questions read this article is enough (Part 1)
Super simple integration of HMS ml kit to realize parent control
ReportingService WebService Form身份验证
Rsync+inotyfy realize real-time synchronization of single data monitoring
Huawei 2020 school recruitment written test programming questions read this article is enough (Part 2)
DeFi 2.0的LaaS协议,重振DeFi赛道发展的关键
Mobile terminal -flex item attribute
量化开发必掌握的30个知识点【什么是分笔逐笔数据】?
DAO赛道异军突起,M-DAO的优势在哪里?
D3.JS 纵向关系图(加箭头,连接线文字描述)
与张小姐的春夏秋冬(3)
我的理想工作,码农的绝对自由支配才是最重要的——未来创业的追求
Training log 6 of the project "construction of Shandong University mobile Internet development technology teaching website"
Crypto giants all in metauniverse, and platofarm may break through
Changed crying, and finally solved cannot read properties of undefined (reading 'parsecomponent')
CMD window under Windows connects to MySQL and operates the table
剑指核心-TaoCloud全闪SDS助力构建高性能云服务
北京宝德&TaoCloud共建信创之路