Java 1.5 starts, provides the thread pool for everybody to use, the function is quite complete. The following is a simple example. The complex example will be placed in a few blogs later.
Import java.util.List; Import Java.util.concurrent.ExecutorService; Import java.util.concurrent.Executors; Import Java.util.concurrent.TimeUnit; /** * Fixed size thread pool * * @author yiding.he */public class Fixedthreadpooldemo {public static void main (string[] args) {//Create a A maximum of 3 tasks running at the same time thread pool Executorservice service = Executors.newfixedthreadpool (3); Schedule a number of tasks to run Service.execute (new Runnableimpl (1)); Service.execute (New Runnableimpl (2)); Service.execute (New Runnableimpl (3)); Service.execute (New Runnableimpl (4)); Service.execute (New Runnableimpl (5)); Service.execute (New Runnableimpl (6)); Service.execute (New Runnableimpl (7)); Service.execute (New Runnableimpl (8)); Service.execute (New Runnableimpl (9)); Service.execute (New Runnableimpl (10)); Service.execute (New Runnableimpl (11)); Service.execute (New Runnableimpl (12)); Service.execute (New Runnableimpl (13)); Service.execute (New Runnableimpl (14)); Service.execute (New Runnableimpl (15)); End the thread pool. Shutdown () does not end immediately, but waits for all scheduled tasks to finish. Service.shutdown (); //If you do not want to end immediately, and do not intend to wait too long, then you can call the Awaittermination () method to wait for a while to try {service.awaittermination (5, timeunit.seconds); System.err.println ("Waiting time has passed"); Shutdownnow () Discards all waiting tasks and ends the thread pool after the currently executing task completes. 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; priv ATE runnableimpl (int id) {this.id = ID;} public void Run () {System.out.println ("execute" + ID); try {thread.sleep (2000); The catch (Interruptedexception e) {//Nothing Todo} System.out.println (ID +) was completed. "); } @Override public String toString () {return "thread" + ID;}} }