Here is simply a small application of a thread pool, the number of threads accessed from the console input threads, the name of the thread that outputs the work, and the first to construct an object containing 5 threads.
Code:
ImportJava.util.Scanner;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classThreadd { Public Static voidMain (string[] args) {//TODO auto-generated Method StubScanner s =NewScanner (system.in); Executorservice es= Executors.newfixedthreadpool (5);//Initialize five threads, use when used, suspend without accessRunn r =NewRunn (); inti = Integer.parseint (S.nextline ());//the number of threads that work from the console here while(--i>0) {Es.execute (R); } while(true){ if(es.isterminated ()) {System.out.println ("The thread task has already been completed"); Break; }} es.shutdown (); Try{Thread.Sleep (1000); if(Es.isshutdown ()) {System.out.println ("The thread pool has been destroyed. "); } } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}classRunnImplementsrunnable{@Override Public voidrun () {//TODO auto-generated Method StubSystem.out.println (Thread.CurrentThread (). GetName () + "Running"); } }
Input: 7
Output: Pool-1-thread-1 is running
Pool-1-thread-3 is running
Pool-1-thread-2 is running
Pool-1-thread-4 is running
Pool-1-thread-2 is running
Pool-1-thread-5 is running
Thread pool application of Java programming