In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "how to apply CyclicBarrier cycle barrier in Java", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this article "how to apply CyclicBarrier cycle barrier in Java".
I. brief introduction
CyclicBarrier literally means loop fence (loop barrier), which allows a group of threads to wait to a certain state (barrier point) and then all execute at the same time. It is called a loopback because CyclicBarrier can be reused when all waiting threads are released.
The role of CyclicBarrier is to make a group of threads wait for each other, and when a common point is reached, all previously waiting threads continue to execute, and the CyclicBarrier function can be reused.
II. The use of CyclicBarrier
Construction method:
/ / parties represents the number of threads blocked by the barrier, and each thread calls the await method to tell CyclicBarrier that I have reached the barrier, and then the current thread is blocked. Public CyclicBarrier (int parties) / / is used to give priority to the execution of barrierAction when the thread reaches the barrier, making it easier to handle more complex business scenarios (the thread is executed after the barrier is reached)
Important methods:
/ / when all the specified number of threads call the await () method, these threads no longer block / / BrokenBarrierException indicates that the fence has been broken, probably because one of the threads await () was interrupted or timed out public int await () throws InterruptedException, BrokenBarrierExceptionpublic int await (long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException// loop can reset the CyclicBarrier application scenario through the reset () method
Using CyclicBarrier can be used for multi-thread calculation of data, and finally merge the results of the scenario.
The counters of CyclicBarrier can be reset and the barrier can be reused to support scenarios like "full departure".
Simulate merging computing scenarios
Using CyclicBarrier can be used for multi-thread calculation of data, and finally merge the results of the scenario.
Public class CyclicBarrierTest2 {/ / saves each student's grade point average private ConcurrentHashMap map=new ConcurrentHashMap (); private ExecutorService threadPool= Executors.newFixedThreadPool (3); private CyclicBarrier cb=new CyclicBarrier (3, ()-> {int result=0; Set set = map.keySet (); for (String s:set) {result+=map.get (s)) } System.out.println ("the average score of the trio is:" + (result/3) + "score");}); public void count () {for (int itemosi new Thread (r, counter.addAndGet (1) + "number"), new ThreadPoolExecutor.AbortPolicy ()) CyclicBarrier cyclicBarrier = new CyclicBarrier (5, ()-> System.out.println); for (int I = 0; I < 10; iTunes +) {threadPoolExecutor.submit (new Runner (cyclicBarrier));}} static class Runner extends Thread {private CyclicBarrier cyclicBarrier; public Runner (CyclicBarrier cyclicBarrier) {this.cyclicBarrier = cyclicBarrier } @ Override public void run () {try {int sleepMills = ThreadLocalRandom.current (). NextInt (1000); Thread.sleep (sleepMills); System.out.println (Thread.currentThread (). GetName () + "contestant is in place, ready to share:" + sleepMills + "ms" + cyclicBarrier.getNumberWaiting ()) CyclicBarrier.await ();} catch (InterruptedException e) {e.printStackTrace ();} catch (BrokenBarrierException e) {e.printStackTrace ();}
Output result:
Contestant No. 3 is in position, ready to share: 78ms0
Contestant No. 1 is in position, ready to share: 395ms1
Contestant No. 5 is in position, ready to share: 733ms2
Contestant No. 2 is in position, ready to share: 776ms3
Contestant No. 4 is in position, ready to share: 807ms4
Referee: the game begins.
Contestant No. 4 is in position, ready to share: 131ms0
Contestant No. 3 is in position, ready to share: 256ms1
Contestant No. 2 is in position, ready to share: 291ms2
Contestant No. 1 is in position, ready to share: 588ms3
Contestant No. 5 is in position, ready to share: 763ms4
Referee: the game begins.
Third, CyclicBarrier source code analysis CyclicBarrier process
The main process is:
Acquire lock if count! = 0, enter blocking
Before entering the blocking, you first need to enter the conditional queue, then release the lock, and finally block
If count! = 0 does a wake-up call, the nodes in all conditional queues are converted to blocking queues
After being awakened, the lock will be acquired. If the lock acquisition fails, it will enter the blocking queue of lock.
If the lock is acquired successfully, the lock is released, and the thread in the queue is awakened and synchronized.
Here is a simple flowchart:
Here are some specific code invocation processes:
How many common questions are there?
1. A group of threads wait for each other before triggering the barrier, and how is the wake-up logic implemented when the last thread reaches the barrier. The process of waking up is to wake up all nodes on the conditional queue by calling java.util.concurrent.locks.Condition#signalAll.
two。 How is the recycling of deleted columns realized? In fact, a mutex ReentrantLock's conditional queue and blocking queue conversion.
3. The logic of the conversion from conditional queue to synchronous queue? During the conversion process, it will first wake up all blocked threads in the conditional queue, and then go to get the lock. If the fetch fails, it will enter the synchronization queue.
The difference between CyclicBarrier and CountDownLatch
Counters for CountDownLatch can only be used once, while counters for CyclicBarrier can be reset using the reset () method. So CyclicBarrier can handle more complex business scenarios, such as if the calculation goes wrong, you can reset the counter and let the threads execute it again.
CyclicBarrier also provides methods such as getNumberWaiting, which can get the number of threads blocked by CyclicBarrier, and isBroken, which is used to know whether blocked threads are interrupted or not.
CountDownLatch blocks the main thread, and CyclicBarrier does not block the main thread, only child threads.
Both CountDownLatch and CyclicBarrier can wait between threads, but they have different priorities. CountDownLatch is typically used by one or more threads, waiting for other threads to finish the task before executing. CyclicBarrier is typically used when a group of threads waits for each other to a certain state, and then that group of threads executes at the same time.
CyclicBarrier can also provide a barrierAction that merges the results of multithreaded calculations.
CyclicBarrier wakes up the blocking of a group of threads through ReentrantLock's "exclusive lock" and Conditon, while CountDownLatch is realized through AQS's "shared lock".
The above is about the content of this article on "how to apply the CyclicBarrier cycle barrier in Java". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.