The main thread waits for all tasks in the thread pool to be completed.

Source: Internet
Author: User

When a multi-threaded program is compiled using a thread pool, some statistics are required when all tasks are completed. Statistics must be completed in all tasks. So let the main thread wait for all tasks to complete. You can use ThreadPoolExecutor. awaitTermination (long timeout, TimeUnit unit ). See the sample code:

Package com. chenlb;
 
Import java. util. Random;
Import java. util. concurrent. Define blockingqueue;
Import java. util. concurrent. ThreadPoolExecutor;
Import java. util. concurrent. TimeUnit;
 
/**
* Example of thread pool usage. The main thread waits until all tasks are completed and then ends.
*
* @ Author chenlb 10:31:03
*/
Public class ThreadPoolUse {
 
Public static class MyTask implements Runnable {
Private static int id = 0;
 
Private String name = "task-" + (++ id );
Private int sleep;
 
Public MyTask (int sleep ){
Super ();
This. sleep = sleep;
}
 
Public void run (){
System. out. println (name + "----- start -----");
Try {
Thread. sleep (sleep); // simulate task execution.
} Catch (InterruptedException e ){
E. printStackTrace ();
}
System. out. println (name + "----- end" + sleep + "-----");
}
 
}
 
Public static void main (String [] args ){
System. out. println ("============================ start ====================== ");
ThreadPoolExecutor executor = new ThreadPoolExecutor (5, 5, 60, TimeUnit. SECONDS, new LinkedBlockingQueue <Runnable> ());
Int n = 10;
Int sleep = 10*1000; // 10 s
Random rm = new Random ();
For (int I = 0; I <n; I ++ ){
Executor.exe cute (new MyTask (rm. nextInt (sleep) + 1 ));
}
 
Executor. shutdown ();
 
Try {
Boolean loop = true;
Do {// wait until all tasks are completed
Loop =! Executor. awaitTermination (2, TimeUnit. SECONDS );
} While (loop );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
 
System. out. println ("======================================================== = ");
}
 
}
Of course there are other methods.

Author "thinking in hadoop"
 

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.