Concurrent Programming -- locking countdownlatch and barrier

Source: Internet
Author: User

Java concurrent programming practice directory

Concurrent Programming-concurrenthashmap

Concurrent Programming-blocking queue and producer-consumer Mode

Concurrent Programming -- locking countdownlatch and barrier

 

Overview

Part 1 locking

Part 1 fence

Reference

 

Part 1 locking

Locking is a synchronization tool class that can delay the progress of a thread until it reaches the termination state. Locking is equivalent to a door: the door is closed until it reaches the end state, and no thread can pass. When it reaches the end state, this door will open and allow all threads to pass. When the lock reaches the end state, the status will not change, so this will remain open forever. Blocking can be used to ensure that certain activities are not executed until other activities are completed. For example:

  • Make sure that a computing task is executed after all required resources are initialized.
  • Make sure that a service is started only after all other services on which it depends are started.
  • Wait until all participants in an operation are ready to continue.

Countdownlatch is a flexible locking implementation that can be used in the above cases. It can make one or more threads wait for a group of events. The lock status includes a counter, Which is initialized to a positive number, indicating the number of events to wait. Countdown indicates that an event has occurred while the await method waits for the counter to reach 0. This indicates that all the events that need to be waited have occurred. If the counter value is non-zero, await will be blocked until the counter is zero, the waiting thread is interrupted, or the waiting timeout.

The following testharness program provides two common locking methods. Testharness creates a certain number of threads and uses them to concurrently execute specified tasks. It uses two locks to indicate "Start door" and "End Door" respectively ". The initial value of the Start door counter is 1, and the initial value of the End Door counter is the number of working threads. Each worker thread must first wait on the startup door to ensure that all threads are ready before execution starts. The last thing each thread needs to do is to reduce the countdown method of the call termination gate by 1, which enables the main thread to wait until all the worker threads have completed the execution, therefore, the time consumed can be counted.

1 package COM. concurrency. basicbuildingblocks_5; 2 3 Import Java. util. concurrent. countdownlatch; 4 5/** 6*5.11 use countdownlatch in timing testing to start and stop threads (locking) 7*8 * @ classname: testharness 9 * todo10 * @ author xingle11 * @ date 2014-9-4 PM 2: 56: 2912 */13 public class testharness {14 15 int nthreads; 16 runnable task; 17 Public testharness (INT nthreads, runnable task) {18 this. nthreads = nthreads; 19 this. task = task; 20} 21 public long timetask () {22 23 // start door 24 final countdownlatch startgate = new countdownlatch (1 ); 25 // closing door 26 final countdownlatch endgate = new countdownlatch (nthreads); 27 for (INT I = 0; I <nthreads; I ++) {28 thread = new thread () {29 public void run () {30 // each thread waits on the startup door, make sure that all threads are ready before starting 31 try {32 startgate. await (); // wait until the counter reaches 0 33 try {34 task. run (); 35} finally {36 // after each thread ends, the countdown decreasing counter is called, indicating that an event occurs 37 endgate. countdown (); 38} 39} catch (interruptedexception e) {40 E. printstacktrace (); 41} 42 43} 44}; 45 thread. start (); 46} 47 long start = system. nanotime (); 48 // when the start door occurs 49 startgate. countdown (); 50 try {51 // wait until the end of the thread all end 52 endgate. await (); 53} catch (interruptedexception e) {54 E. printstacktrace (); 55} 56 long end = system. nanotime (); 57 Return end-start; 58} 59}

 

Test procedure:

1 package COM. concurrency. basicbuildingblocks_5; 2 3/** 4*5 * @ classname: testharnessmain 6 * todo 7 * @ author xingle 8 * @ date 2014-9-4 3:27:18 9 */10 public class testharnessmain {11 12 public static void main (string [] ARGs) {13 runnable task = new runnable () {14 15 @ override16 public void run () {17 system. out. println ("execution task, I am a thread:" + thread. currentthread (). getname (); 18} 19}; 20 int COUNT = 10; 21 testharness = new testharness (count, task); 22 long time = testharness. timetask (); 23 system. out. println ("blocking test result execution" + Count + "Threads" + "Total time:" + time); 24} 25}

 

Execution result:

Part 1 fence

You can see that you can start a group of related operations by locking them, or wait for the completion of a group of related operations. Locking is a one-time object. Once it is terminated, it cannot be reset.

Barrier is similar to blocking, which can block a group of threads until an event occurs. The key difference between a barrier and a lock is that all threads must reach the barrier position at the same time to continue execution. Blocking is used to wait for events, while barrier is used to wait for other threads. (All threads wait for each other until all threads reach a certain point. Then, the thread can continue to run .)

Cyclicbarrier allows a certain number of participants to gather at the barrier position repeatedly, which is very useful in parallel Iteration Algorithms.CyclicbarrierSupports an optionalRunnableParameter. When the thread passes through the barrier, the runnable object is called. ConstructorCyclicBarrier(int parties, Runnable barrierAction)When the threadCyclicbarrierObject callawait()When the counter is setpartiesThe fence will open.

1 package COM. concurrency. basicbuildingblocks_5; 2 3 Import Java. util. concurrent. brokenbarrierexception; 4 Import Java. util. concurrent. cyclicbarrier; 5 6/** 7*8 * @ classname: worker 9 * @ author xingle10 * @ date 2014-9-9 am 10: 41: 1711 */12 public class worker implements runnable {13 14 Final int ID; 15 final javasicbarrier barrier; 16 17 public worker (int id, javasicbarrier barrier) {18 this. id = ID; 1 9 This. Barrier = barrier; 20} 21 22 @ override23 public void run () {24 system. Out. println (this. ID + "start to run! "); 25 try {26 This. barrier. await (); 27} catch (interruptedexception e) {28 E. printstacktrace (); 29} catch (brokenbarrierexception e) {30 E. printstacktrace (); 31} 32 33} 34 35}

 

Test procedure:

1 package COM. concurrency. basicbuildingblocks_5; 2 3 Import Java. util. concurrent. cyclicbarrier; 4 5/** 6*7 * @ classname: Beer 8 * five people participate in the running. It is stipulated that if all five people reach the end, everyone can drink beer. However, as long as one person does not reach the end, they cannot drink. There is no requirement to start running 9 * @ author xingle10 * @ date 2014-9-9 am 10: 40: 3611 */12 public class beer {13 public static void main (string [] ARGs) {14 Final int COUNT = 5; 15 final fetch icbarrier barrier = new fetch icbarrier (count, new runnable () {16 17 @ override18 public void run () {19 system. out. println ("Drink beer! "); 20} 21}); 22 23 for (INT I = 0; I <count; I ++) {24 new thread (new worker (I, barrier )). start (); 25} 26} 27 28}

 

Execution result:

 

 

Refer:

1. concurrent programming practices 5.5 synchronization tools

2. Try to distinguish cyclicbarrier from countdownlatch in terms of popularity.

 

Concurrent Programming -- locking countdownlatch and barrier

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.