[Reprint] Java Multithreaded learning-java.util.concurrent detailed (a) latch/barrier

Source: Internet
Author: User

Reprinted from http://janeky.iteye.com/blog/769965

JAVA1.5 provides a highly efficient and practical multithreaded package: Java.util.concurrent, which provides a number of advanced tools to help developers write efficient, maintainable, and well-structured Java multithreaded applications. From this blog, I will work with you to learn these new Java multithreaded components

1.CountDownLatch
Let's start by learning more about this class in the JDK1.5 API:
"A synchronous helper class that allows one or more threads to wait until a set of operations that are being performed in another thread is completed. Initializes the countdownlatch with the given count. Because the countdown () method is called, the await method is blocked until the current count reaches 0. After that, all the waiting threads are freed, and all subsequent calls to await are returned immediately. This behavior occurs only once-the count cannot be reset. If you need to reset the count, consider using Cyclicbarrier. ”

This means that countdownlatch can be used to manage a set of related thread executions by calling the Countdownlatch await method (which is blocked) in the main thread, allowing each thread to invoke the Countdown method. When all the threads have just finished countdown, await also returns smoothly, no longer blocked. This is especially true in situations where a task is divided into threads that are executed until all threads are executed and then summarized.

Let me give you a very simple example. Let's say we're going to print 1-100 and then output "OK". 1-100 printing order does not require unification, just ensure that "OK" is in the last appearance.

Solution: We define a countdownlatch and then open 10 threads to print (n-1) *10+1 to (n-1) *10+10 respectively. The await method is called in the main thread to wait for all threads to finish executing, and the countdown method is called after each thread finishes executing. Finally, await return and print "OK".

The specific code is as follows (this code references the JDK sample code):
Java code
  1. Import Java.util.concurrent.CountDownLatch;
  2. /**
  3. * Example: Examples of use of Countdownlatch
  4. * Mail: [email protected]
  5. * @author Janeky
  6. */
  7. Public class Testcountdownlatch {
  8. private static final int N = 10;
  9. public static void Main (string[] args) throws interruptedexception {
  10. Countdownlatch donesignal = new Countdownlatch (N);
  11. Countdownlatch startsignal = new Countdownlatch (1); Start signal execution
  12. For (int i = 1; I <= N; i++) {
  13. New Thread (new Worker (i, donesignal, startsignal)). Start (); Thread started.
  14. }
  15. SYSTEM.OUT.PRINTLN ("begin------------");
  16. Startsignal.countdown (); //Start execution
  17. Donesignal.await (); //wait for all threads to finish executing
  18. System.out.println ("OK");
  19. }
  20. static class Worker implements Runnable {
  21. Private final Countdownlatch donesignal;
  22. Private final Countdownlatch startsignal;
  23. private int beginindex;
  24. Worker (int beginindex, Countdownlatch donesignal,
  25. Countdownlatch startsignal) {
  26. this.startsignal = startsignal;
  27. this.beginindex = beginindex;
  28. this.donesignal = donesignal;
  29. }
  30. public Void Run () {
  31. try {
  32. Startsignal.await (); //Wait to start the release of the signal
  33. Beginindex = (Beginindex- 1) * ten + 1;
  34. For (int i = beginindex; I <= beginindex + i++) {
  35. System.out.println (i);
  36. }
  37. } catch (Interruptedexception e) {
  38. E.printstacktrace ();
  39. } finally {
  40. Donesignal.countdown ();
  41. }
  42. }
  43. }
  44. }


Summary: Coundownlatch is useful for managing a set of related threads. Two usage scenarios are depicted visually in the example code above. The first is a calculator of 1, which represents two states, switches. The second is that the counter is N, which means waiting for n operations to complete. We can use this component to manage the execution of a set of independent threads in the future when we are writing multi-threaded programming.

2.CyclicBarrier
Let's start by learning more about this class in the JDK1.5 API:
"A synchronization helper class that allows a group of threads to wait on each other until a common barrier point (common barrier points) is reached. In programs that involve a set of fixed-size threads, these threads have to wait for each other, and cyclicbarrier is useful at this time. Because the barrier can be reused after releasing the waiting thread, it is called a cyclic barrier.
Cyclicbarrier supports an optional Runnable command that runs only once at each barrier point after the last thread in a set of threads arrives (but before releasing all threads). This barrier operation is useful if you update the shared state before continuing with all participating threads.

We talked about Cyclicbarrier when we were studying countdownlatch. What is the connection between the two? Refer to the description in [Jcip], "The key difference is and a barrier, all the threads must come together at a barrier point at the same Time in order to proceed. Latches is for waiting for events; Barriers is for waiting to other threads. Cyclicbarrier waits for all threads to complete together before performing an action. This is also possible with the Countdownlatch function. But countdownlatch more often waits for an event to happen. In Cyclicbarrier, all threads call the await method, waiting for the other threads to finish executing.

To give a very simple example, tonight our Buddies 4 go to happy. On each other's notice: Eight o'clock in the evening to XX bar in front of the assembly, see not scattered! There is a friend living near, early on. Some of the affairs are busy, just casing. No matter what, first-come can not act alone, can only wait for everyone

The code is as follows (refer to some tutorials on the web)
Java code
  1. Import Java.util.Random;
  2. Import java.util.concurrent.BrokenBarrierException;
  3. Import Java.util.concurrent.CyclicBarrier;
  4. Import Java.util.concurrent.ExecutorService;
  5. Import java.util.concurrent.Executors;
  6. Public class Testcyclicbarrier {
  7. public static void Main (string[] args) {
  8. Executorservice exec = Executors.newcachedthreadpool ();
  9. final random random=new Random ();
  10. final Cyclicbarrier barrier=new Cyclicbarrier (4,new Runnable () {
  11. @Override
  12. public Void Run () {
  13. System.out.println ("Everyone is here, start happy");
  14. }});
  15. For (int i=0;i<4;i++) {
  16. Exec.execute (new Runnable () {
  17. @Override
  18. public Void Run () {
  19. try {
  20. Thread.Sleep (Random.nextint (1000));
  21. } catch (Interruptedexception e) {
  22. E.printstacktrace ();
  23. }
  24. System.out.println (Thread.CurrentThread (). GetName () +"Come, Other Buddies");
  25. try {
  26. Barrier.await (); //wait for other buddies
  27. } catch (Interruptedexception e) {
  28. E.printstacktrace ();
  29. } catch (Brokenbarrierexception e) {
  30. E.printstacktrace ();
  31. }
  32. }});
  33. }
  34. Exec.shutdown ();
  35. }
  36. }


About the await method pay special attention to the possibility that it may be interrupted for some reason during the blocking process.

Summary: Cyclicbarrier is a fence that waits for all threads to arrive before performing related operations. Barrier can be reused after releasing the wait thread.

[Reprint] Java Multithreaded learning-java.util.concurrent detailed (a) latch/barrier

Related Article

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.