Java Multi-thread Countdownlatch

Source: Internet
Author: User

Pre-order:

Last week, the module developed by the developer of the Dev was presented with a bug, and it was still an occasional occurrence.

After careful review of the code, it was found that multiple threads were enabled in the business and 2 threads were running at the same time, but the newly started 2 threads had to ensure that one completed and the other continued to run before the bug could be eliminated.

When do you use it?

Multithreading is used in many places, but if we want to implement another thread after a particular thread has run, Countdownlatch can come in handy.

How to use it?

Let's look at common multithreaded code:

1  PackageCode;2 3  Public classMyThreadextendsThread {4      Public Static voidMain (string[] args) {5MyThread th =NewMyThread (); 6Thread T1 =NewThread (Th, "Mythread")); 7 T1.start (); 8 System.out.println (Thread.CurrentThread (). GetName ()); 9         }        Ten          Public voidRun () One             {      AMythread1 Th2 =NewMythread1 ();  -Thread t2 =NewThread (Th2, "Mythread1");  - T2.start ();  theSystem.out.println ( This. CurrentThread (). GetName ());  -             }   -         classMythread1extendsThread -         { +              Public voidrun () { -                 Try { +Thread.Sleep (1000); A}Catch(interruptedexception e) { at                     //TODO auto-generated Catch block - e.printstacktrace (); -                 } -System.out.println ( This. CurrentThread (). GetName ());  -                 }   -              in         } -}

Code as above, the first with mythread inherited the thread class, and then in the Mythread class and write a MyThread1 class, the same is inherited the thread class, and in the Run method to sleep 1 seconds, so that the running code, will print out:

As you can see from the output sequence above, first the main thread is started, then the Mythread thread is started, and the MYTHREAD1 thread is started in the mythread thread. But by letting the MyThread1 thread sleep for 1 seconds, the simulation deals with the subsequent business so that he runs out of time later than Mythread.

Now, add the Countdownlatch to the code, let MyThread1 run it first, and let Mythread continue to run.

1  PackageCode;2 3 ImportJava.util.concurrent.CountDownLatch;4 5  Public classMyThreadextendsThread {6Countdownlatch Countdownlatch =NewCountdownlatch (1);7      Public Static voidMain (string[] args) {8MyThread th =NewMyThread (); 9Thread T1 =NewThread (Th, "Mythread")); Ten T1.start ();  One System.out.println (Thread.CurrentThread (). GetName ());  A         }         -          Public voidRun () -             {      theMythread1 Th2 =NewMythread1 ();  -Thread t2 =NewThread (Th2, "Mythread1");  - T2.start ();  -                 Try { + countdownlatch.await (); -}Catch(interruptedexception e) { + e.printstacktrace (); A                 } atSystem.out.println ( This. CurrentThread (). GetName ());  -             }   -         classMythread1extendsThread -         { -              Public voidrun () { -                 Try { inThread.Sleep (1000); -}Catch(interruptedexception e) { to e.printstacktrace (); +                 } -System.out.println ( This. CurrentThread (). GetName ());  the Countdownlatch.countdown (); *                 }   $             Panax Notoginseng         } -}

The code is written as shown above, and is roughly three steps

1, we're going to start with a new Countdownlatch object into the parameter set to 1 (I personally understand that this is like a new array, when the array is emptied, then the interrupted thread can continue to run)

2, call Countdownlatch.await () in the Mythread class, and let the current thread stop running.

3, call the Countdownlatch.countdown () method in the Mythread1 class. When the Mythread1 is all executed, and then the method is finally called, the function is to empty the "array" I say.

Look at the output print results

As a result, the results are as expected.

Finally, the countdownlatch countdownlatch = new Countdownlatch (1) of the entry, this block is set to 1, then you need to call Countdownlatch.countdown () minus 1.

If it is a different number, call the corresponding number of times, or the thread calling countdownlatch.await () will not be executed again.

Java Multi-thread Countdownlatch

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.