Application of Countdownlatch in multi-threaded program

Source: Internet
Author: User

I. Countdownlatch INTRODUCTION
Countdownlatch is introduced after JDK1.5, and exists under the Java.util.concurrent package, enabling a thread to wait for another thread to complete the action before executing.
Construction Method:
1   Public Countdownlatch (int  count) {2         ifthrowNew IllegalArgumentException ("Count < 0"); 3          This New Sync (count); 4     }

Main methods:

The countdown () method is called every time, and the counter is reduced by 1

The await () method keeps the current thread in a blocked state, knowing that the counter value is 0

Two. Countdownlatch use
1  Packagecom;2 3 ImportJava.util.*;4 ImportJava.util.concurrent.ConcurrentHashMap;5 ImportJava.util.concurrent.ConcurrentMap;6 ImportJava.util.concurrent.CountDownLatch;7 ImportJava.util.concurrent.atomic.AtomicInteger;8 9 /**Ten * Countdownlatch Test One  */ A classMythread<t>extendsThread { - Countdownlatch Countdownlatch; - map map; the     //constructor, the map is passed in -      PublicMyThread (countdownlatch countdownlatch, map map) { -          This. Countdownlatch =Countdownlatch; -          This. Map =map; +     } -      Public voidrun () { +Map.put (Thread.CurrentThread (). GetName (),NewObject ()); ACountdownlatch.countdown ();//1 Reduction in Countdown counter once thread executes at     } - } -  -  Public classtestthreadandcollection { -      Public Static voidMain (string[] args)throwsinterruptedexception { -         //indicates a test 100 times in          for(inti = 0; I < 100; i++) { - test (); to         } +     } -  the      Public Static  voidTest ()throwsinterruptedexception { *Countdownlatch latch =NewCountdownlatch (2000); $         //using HashMap, this is thread insecurePanax Notoginsengmap<string,object> HashMap =NewHashMap (); -         //using Concurrenthashmap, thread-safe the         //map<string,object> concurrenthashmap = new Concurrenthashmap (); +         //Two for loop, 2000 Threads A          for(inti = 0; i < 1000; i++) { the             //Multithreaded HashMap Testing +             //myThread mthread = new MyThread (latch, hashMap); -             //multithreaded Concurrenthashmap Testing $MyThread Mthread =NewmyThread (latch, hashMap); $ Mthread.start (); -         } -          for(inti = 0; i < 1000; i++) { theMyThread Mthread =NewmyThread (latch, hashMap); - Mthread.start ();Wuyi         } the         //wait for all the current child threads to finish, here is the main thread waiting, and then output the size - latch.await (); Wu         //here is the main thread sleep for a period of time (1 seconds), the effect with latch.await (); -        /*try{ About System.out.println (Thread.CurrentThread (). GetName ());//When the front-line output is the main $ Thread.Sleep (+); - }catch (interruptedexception e) { - e.printstacktrace (); -         }*/ A         //System.out.println (Concurrenthashmap.size ()); + System.out.println (Hashmap.size ()); the     } -}

Because the HashMap under multithreading is unsafe, the result:

While Concurrenthashmap is thread-safe, the results are as follows:

Concurrenthashmap, if the countdownlatch latch = new Countdownlatch (2000), the parameter 2000 is changed to a value less than 2000 (1000) Then the result of the output is as follows:

Because the countdown () counter is decremented to 0, the await () method will no longer block the main thread, so the execution of the output statement may occur before all threads are put, so the result is not 2000

 

Application of Countdownlatch in multi-threaded program

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.