Java Multithreading-Concurrency Tool Class (ii) Countdownlatch__java waiting for multithreading to complete

Source: Internet
Author: User
Reference: https://www.jianshu.com/p/1716ce690637
http://ifeve.com/talk-concurrency-countdownlatch/

What's countdownlatch?

Countdownlatch is also called latching, which is introduced in JDK1.5, allowing one or more threads to wait for another thread to complete the operation before executing.

Countdownlatch internally maintains a counter with an initial value of the number of threads, the main thread executes the await method, and if the counter is greater than 0, the wait is blocked. When a thread completes a task, the counter value is reduced by 1. When the counter is 0 o'clock, all threads have completed the task, and the waiting main thread is awakened to continue execution. Application Scenarios

The main thread of the application wants to execute after the threads responsible for starting the framework service have completed. In this requirement, the easiest way to implement the main thread waiting for all threads to do is to use join. However, the countdownlatch provided in the concurrency package after JDK1.5 can also implement this function of join, and more than the join function.

Example 1:

public class Startupcheckservice {private SimpleDateFormat SDF = new SimpleDateFormat ("[Yyyy-mm-dd HH:mm:ss:SSS]");
	private void println (String msg) {System.out.println (Sdf.format (New Date ()) + msg);

	    /** * The base class of all services, implemented in the Execute method implementation */class service implements Runnable {private Countdownlatch latch;
	    Public Service (Countdownlatch latch) {this.latch = latch;
	        @Override public void Run () {try {execute ();
	        finally {if (latch!= null) Latch.countdown (); The public void execute () {}}/** * Service specifically implements the class. Work 2 seconds * * Class Healthcheckservice extends service {p
	    Ublic healthcheckservice (Countdownlatch latch) {super (latch);
	            @Override public void Execute () {try {println ("Healthcheckservice work ...");
	            TimeUnit.SECONDS.sleep (2);
	        println ("Healthcheckservice done ..."); Catch (Interruptedexception e)
	        {E.printstacktrace (); }}/** * Service specific implementation class. Work 3 seconds * * Class Databasecheckservice extends Service {public Databasecheckservice (Co
	    Untdownlatch latch) {super (latch);
	            @Override public void Execute () {try {println ("Databasecheckservice work ...");
	            TimeUnit.SECONDS.sleep (3);
	        println ("Databasecheckservice done ...");
	        catch (Interruptedexception e) {e.printstacktrace (); }}/** * Applies the startup class to perform the tasks for each service using the thread pool.
	 is responsible for initializing the latch, and then waiting until all the services have been detected.
	    * * Class Application {private Countdownlatch latch;
	        public void StartUp () throws Exception {latch = new Countdownlatch (2);
	        list<service> Services = new arraylist<> ();
	        Services.add (new Databasecheckservice (latch));
	        Services.add (new Healthcheckservice (latch)); Executorservice executor = Executors.newfixedthreadpool (ServicEs.size ());
	        for (service service:services) {Executor.execute (service);
	        } latch.await ();
	        println ("All service are start up");
	    Executor.shutdown ();
		} public static void Main (String arg[]) {try {new Startupcheckservice (). New application (). StartUp ();
		catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
 }
	}
}

Output:


Example 2:

public class Test {public static void main (string[] args) {final Countdownlatch latch = new Countdownlatch (2); New Thread () {public void run () {try {System.out.println ("Child Threads" + thread.currentthread (). GetName () + "executing")
					;
					Thread.Sleep (3000);
					SYSTEM.OUT.PRINTLN ("Child Threads" + thread.currentthread (). GetName () + "execution completed");
				Latch.countdown ();
				catch (Interruptedexception e) {e.printstacktrace ();
		}
			};

		}.start (); New Thread () {public void run () {try {System.out.println ("Child Threads" + thread.currentthread (). GetName () + "executing")
					;
					Thread.Sleep (3000);
					SYSTEM.OUT.PRINTLN ("Child Threads" + thread.currentthread (). GetName () + "execution completed");
				Latch.countdown ();
				catch (Interruptedexception e) {e.printstacktrace ();
		}
			};

		}.start ();
			try {System.out.println ("Wait 2 child threads complete ...");
			Latch.await ();
			System.out.println ("2 child threads have been executed");
		System.out.println ("Continue to execute the main thread"); catch (Interruptedexception e) {e.printstacktrace ();
		}
	}
} 

Output:

Child thread Thread-0 is executing
waiting for 2 child threads to finish ...
Child thread Thread-1 executing
child thread Thread-1 execution
child thread Thread-0 execution completed
2 child threads have been executed
continue to execute the main thread
the difference between Cyclicbarrier and CountdownlatchCountdownlatch counters can only be used once. The Cyclicbarrier counter can be reset using the Reset () method. So cyclicbarrier can handle more complex business scenarios, such as if the calculation is wrong, you can reset the counters and let the threads do it again. Cyclicbarrier also provides other useful methods, such as Getnumberwaiting method to obtain the number of threads Cyclicbarrier blocked. The IsBroken method is used to know if a blocked thread is interrupted. Countdownlatch and Cyclicbarrier both have the ability to wait between threads, but they have different emphases: Countdownlatch is typically used by a thread A to wait for several other threads to perform a task before it executes , and Cyclicbarrier is typically used for a set of threads to wait to a certain state, and then the group of threads executes concurrently;

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.