Building a thread pool, you can create threads in the pool, use this thread pool to handle things, and then assign processing to threads in a thread pool, depending on the actual situation.
public class Testthreadpool {public static void main (string[] args) {//executorservice EC = Executors.newfixedthreadpool ( 3)///fixed thread number//executorservice EC =executors.newcachedthreadpool ();//cache thread pool, automatically creates threads executorservice EC = Executors.newsinglethreadexecutor ();//Always keep a thread dead creates a new for (int j = 1; J <; J + +) {Final int task = j;//inner class Ec.execute (n EW Thread () {public void run () {try {Thread.Sleep ($)} catch (Interruptedexception e) {e.printstacktrace ()} for (int i = 1; i < i++) {System.out.println ("Each thread executes the action:" + i + "task number" + Task);}};}); Ec.shutdown ();}}
If you create a fixed value of 3, you will find that the results are always 3 groups, and the first three immediately after processing the 3
If the cache thread pool is created, the number of threads will be processed according to the actual situation.
If you create a singleton thread pool, the results are found to be output sequentially
Java thread pool