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"