Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use java counter CountDownLatch

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces "how to use java counter CountDownLatch" related knowledge, in the actual case operation process, many people will encounter such a dilemma, then let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!

Introduction to CountDownLatch

CountDownLatch as the name implies, count + down + latch = count + minus + latch (so split is also easy to remember = _ =) can understand that this thing is a counter, can only be subtracted but not added, and it also has the function of a latch, when the counter is not 0, the latch is locked; when the counter is reduced to 0, the latch is opened.

If you feel confused, you can compare the examinee to hand in the examination paper. If the examinee hand in one test paper, the counter will be reduced by one. The invigilator (one or more) cannot leave the examination room until all the examinees have handed in the examination papers (the counter is 0). As for whether the examinee has finished the examination paper, the invigilator does not care. As long as he has handed in the examination papers, he can do the rest of the work.

Principle of CountDownLatch implementation

Let's start with the constructor and explain the principle of the implementation step by step: below the constructor is the source code of the implementation, which is very short, mainly by creating a Sync object.

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

Sync object

Private static final class Sync extends AbstractQueuedSynchronizer {private static final long serialVersionUID = 498226498192 2014374L TincSync (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 zerofor (;) {int c = getState (); if (c = 0) return false;int nextc = cif (compareAndSetState (c, nextc)) return nextc = 0;}

Suppose we create it like this: new CountDownLatch (5). In fact, it is equivalent to new Sync (5), equivalent to setState (5). SetState is actually the total number of shared lock resources, which we can temporarily understand as setting a counter with an initial value of 5.

The tryAcquireShared method actually determines whether the value of the current counter is 0, and returns 1 if it is 0. (when 1 is returned, the lock is acquired successfully, and the awit () method is no longer blocked).

The tryReleaseShared method uses CAS to subtract the counter, and every time we call the countDownLatch.countDown () method, we will eventually call this method and subtract the counter to zero.

CountDownLatch.await ()

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

The code is simple, just one sentence (note that the acquireSharedInterruptibly () method is an abstract class: a method of AbstractQueuedSynchronizer, which is inherited by the Sync we mentioned above), we trace the source code and move on:

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

The source code is also very simple, first determine whether the current thread has been interrupted, if not, call the tryAcquireShared (int acquires) method to determine whether the current thread still needs to be "blocked". In fact, the tryAcquireShared method called here is the java.util.concurrent.CountDownLatch.Sync.tryAcquireShared (int) method we mentioned above.

Of course, when we didn't call the countDownLatch.countDown () method at first, the tryAcquireShared method will definitely return-1 here, because it will enter the doAcquireSharedInterruptibly method.

DoAcquireSharedInterruptibly (int arg)

CountDown () method

/ / the counter minus 1public void countDown () {sync.releaseShared (1);} / calls the releaseShared method public final boolean releaseShared (int arg) {if (tryReleaseShared (arg)) {/ / the counter minus one doReleaseShared (); / / wakes up the successor node. At this time, there may be only thread nodes that have called await () in the queue, or the queue may be listed as empty return true;} return false;}

At this point, we should be well aware of how the countDownLatch.await () method "blocks" the current thread. In fact, to put it bluntly, when you call the countDownLatch.await () method, your current thread will enter a dead loop, in this endless loop, will continue to judge, by calling the tryAcquireShared method, constantly judge the counter we mentioned above, to see if its value is 0 (when it is 0, that is, when we have called enough countDownLatch.countDown () methods), if it is 0 TryAcquireShared returns 1, and the code enters the red box in the figure, then jumps out of the loop and no longer "blocks" the current thread.

It should be noted that if you are in a constant loop, you are not constantly executing the contents of the for loop, because when you call the parkAndCheckInterrupt () method later, LockSupport.park (this) will be called in this method; to suspend the current thread.

Notes on CountDownLatch usage:

1. Only when count is 0, the program after await is enough to execute.

2. The countDown must be written in finally to prevent the program from deadlock when a different path occurs.

Use the scene:

For example, for a marathon, the ranking calculation, the ranking of the contestants, must be calculated after the race, translated into the advance identified by Java, that is, N threads perform the operation, and the main thread waits until the N child threads have finished executing and then continues to execute.

Public static void testCountDownLatch () {int threadCount = 10 new Runnable final CountDownLatch latch = new CountDownLatch (threadCount); for (int iTun0; I < threadCount; iTunes +) {new Thread (new Runnable () {@ Overridepublic void run () {System.out.println ("Thread" + Thread.currentThread (). GetId () + "start"); try {Thread.sleep (1000); System.out.println ("Thread" + Thread.currentThread (). GetId () + "has reached the destination");} catch (InterruptedException e) {e.printStackTrace () } fianlly {latch.countDown ();}). Start ();} try {latch.await ();} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("10 threads have finished executing! Start calculating rankings ");}

Results:

Thread 10 start Thread 13 start Thread 12 start Thread 11 start Thread 14 start Thread 14 start Thread 15 start Thread 16 start Thread 17 start Thread 18 start Thread 19 start Thread 14 has reached the end thread 15 has reached the end thread 13 has reached the end thread 12 has reached the end thread 10 has reached the end thread 11 has reached the end thread 16 has reached the end thread 17 has reached the end thread 18 has reached the end thread 19 has reached the end point 10 threads have finished execution! Start calculating rankings

This is the end of "how to use java counter CountDownLatch". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report