Beginning with Java 1.5, it provides a thread pool for everyone to use. The function is quite complete. The following is a simple example. Complex examples will be put in the following blogs.
Import java. util. List;
Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;
Import java. util. concurrent. TimeUnit;
/**
* Fixed thread pool size
*
* @ Author yiding. he
*/
Public class FixedThreadPoolDemo {
Public static void main (String [] args ){
// Create a thread pool that can run up to three tasks simultaneously
ExecutorService service = Executors. newFixedThreadPool (3 );
// Schedule several tasks to run
Service.exe cute (new RunnableImpl (1 ));
Service.exe cute (new RunnableImpl (2 ));
Service.exe cute (new RunnableImpl (3 ));
Service.exe cute (new RunnableImpl (4 ));
Service.exe cute (new RunnableImpl (5 ));
Service.exe cute (new RunnableImpl (6 ));
Service.exe cute (new RunnableImpl (7 ));
Service.exe cute (new RunnableImpl (8 ));
Service.exe cute (new RunnableImpl (9 ));
Service.exe cute (new RunnableImpl (10 ));
Service.exe cute (new RunnableImpl (11 ));
Service.exe cute (new RunnableImpl (12 ));
Service.exe cute (new RunnableImpl (13 ));
Service.exe cute (new RunnableImpl (14 ));
Service.exe cute (new RunnableImpl (15 ));
// End the thread pool. Shutdown () does not end immediately, but ends after all the scheduled tasks are completed.
Service. shutdown ();
// If you do not want to end immediately and do not want to wait too long, you can call the awaitTermination () method to wait for a while.
Try {
Service. awaitTermination (5, TimeUnit. SECONDS );
System. err. println ("wait time has passed ");
// ShutdownNow () will discard all waiting tasks and end the thread pool after all the currently executed tasks are completed.
List <Runnable> abandoned = service. shutdownNow ();
System. err. println ("abandoned task:" + abandoned );
} Catch (InterruptedException e ){
E. printStackTrace ();
System. exit (-1 );
}
}
/////////////////////////////////////////
Private static class RunnableImpl implements Runnable {
Private int id;
Private RunnableImpl (int id ){
This. id = id;
}
Public void run (){
System. out. println ("start execution" + id );
Try {
Thread. sleep (2000 );
} Catch (InterruptedException e ){
// Nothing to do
}
System. out. println (id + "finished. ");
}
@ Override
Public String toString (){
Return "Thread" + id;
}
}
}