Class Countdownlatch in Java similar to task.wait () in C #

Source: Internet
Author: User

When the main thread opens up multiple sub-threads and requires that these sub-threads perform the main thread after the completion of the execution, the task's wait method can be implemented in C #, whereas in Java there are types of class Countdownlatch, as follows:

 Public Static voidMain (string[] args)throwsinterruptedexception {countdownlatch latch=NewCountdownlatch (3);  for(inti = 0; I < 3; i++) {Thread T=NewThread () { Public voidrun () {Try{Thread.Sleep (2000);//pause for 2 secondsSystem.out.println ("Thread:" + This. GetId () + "Done"); } Catch(interruptedexception e) {e.printstacktrace ();            } latch.countdown ();        }        };    T.start (); } System.out.println ("Wait for 3 threads to complete"); Latch.await ();//thread hangs, waits for 3 threads to finish executing before executing the following contentSystem.out.println ("3 threads have been completed");}

First, we need to define the total number of threads and implement the Countdownlatch class, each of which executes the countdown method, which is equivalent to reducing the number of bus threads by one. When Latch.await () detects that the number of threads is 0, follow-up related methods are executed.

Class Countdownlatch in Java similar to task.wait () in C #

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.