Java multithreading-let the main thread wait for all sub-threads to complete Code Execution

Source: Internet
Author: User

Implemented using the CountDownLatch class

 

 

Main thread

 

Package test;

Import java. util. concurrent. CountDownLatch;

Public class Main {

/**
*
* @ Author Administrator/2012-3-1/09:36:55 AM
*/
Public static void main (String [] args ){

Int threadNum = 10;
CountDownLatch threadSignal = new CountDownLatch (threadNum); // initialize countDown

For (int I = 0; I <threadNum; I ++) {// open threadNum threads

Thread t = new ImportThread (I, threadSignal );
T. start ();
}
Try {
ThreadSignal. await ();
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} // Wait until all sub-threads have finished running
System. out. println (Thread. currentThread (). getName () + "end."); // print the end mark

}

}

 

 

Sub-thread:

Package test;

Import java. util. concurrent. CountDownLatch;

Public class ImportThread extends Thread {
Private CountDownLatch threadsSignal;
 
Private int index;

Public ImportThread (int index, CountDownLatch threadsSignal ){
This. threadsSignal = threadsSignal;
This. index = index;
}

@ Override
Public void run (){
System. out. println (Thread. currentThread (). getName () + "start ...");
// Do somethings
System. out. println (Thread. currentThread (). getName () + "do execute ...");
ThreadsSignal. countDown (); // when the thread ends, the counter minus 1.
System. out. println (Thread. currentThread (). getName () + "end." + threadsSignal. getCount () + "Threads ");
}
}

 

 

 

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.