A simple Java thread pool can be obtained from executors.newfixedthreadpool (int n). This method returns a thread pool with a thread capacity of N. Then execute execution of the executorservice.
Now gives an example.
Package Zhangphil.executorservice;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Zhangphilexecutorservice {//In order to easily understand the concept of thread pool, assume that the capacity is only 2 threads pool. The actual use process can certainly be more! Private final int number = 2;public Zhangphilexecutorservice () {//Creates a thread pool with a capacity of 2. Executorservice pool = executors.newfixedthreadpool (number), for (int i = 0; i <; i++) {Thread t = new Testthread (i); SYSTEM.OUT.PRINTLN ("Thread pool execution Thread ID:" + i);p Ool.execute (t);} Closes the thread pool. Pool.shutdown ();} Private class Testthread extends Thread {private int id;public testthread (int id) {this.id = ID;} @Overridepublic void Run () {System.out.println ("thread:" + ID + "Run ..."); try {thread.sleep (5000);} catch (Exception e) {e.printstacktrace ();} System.out.println ("Thread:" + ID + "End!");}} public static void Main (string[] args) {new Zhangphilexecutorservice ();}}
Output of the run:
Thread pool execution thread id:0 thread pool execution thread id:1 thread pool execution thread id:2 thread pool execution thread Id:3 thread: 0--run ... Thread pool execution Thread Id:4 thread: 1--run ... Thread pool execution thread id:5 thread pool execution thread id:6 thread pool execution thread id:7 thread pool execution thread id:8 thread pool execution thread Id:9 thread: 1--end! Threads: 0--end! Threads: 2--run ... Threads: 3--run ... Threads: 3--End! Threads: 2--End! Threads: 4--run ... Threads: 5--run ... Threads: 4--End! Threads: 5--End! Threads: 6--run ... Threads: 7--run ... Threads: 7--End! Threads: 6--End! Threads: 8--run ... Threads: 9--run ... Threads: 9--End! Threads: 8--end!
Java thread pool: executorservice,executors