1. Background generated by the thread pool
Web services, database access, and so on are required to process a large number of request threads, if each time a new thread is created for each request, the task completes the destruction of the thread, for the server, the creation and destruction of the thread for the resource consumption is relatively large. Therefore, in order to prevent the waste of resources, the thread must be managed. The thread pool is the advanced technique for managing threads.
2. Function of thread pool
2.1 Through the management of the thread, more reasonable and efficient use of resources.
2.2 By maintaining the thread pool, you can save the overhead of creating threads.
3. Use of the thread pool
PackageSe.thread;ImportJava.util.Random;ImportJava.util.concurrent.Executor;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classTreadpooltestextendsThread { Public Static voidMain (string[] args) {treadpooltest treadpooltest=Newtreadpooltest (); Treadpooltest.start (); } @Override Public voidrun () {Executorservice Executorservice= Executors.newfixedthreadpool (2); for(inti = 0; I < 100; i++) {Runnable Runnable=NewRunnable () {@Override Public voidrun () {LongTime = (Long) (Math.random () *1000); System.out.println ("Rest Time:" +time+ "MS"); Try{thread.sleep (time); } Catch(interruptedexception e) {e.printstacktrace (); } } }; Executorservice.execute (runnable); } executorservice.shutdown (); }}
Note: 1. The thread pool must be closed using the shutdown display.
2. In the For loop, it is common to wait for the thread pool to be idle, causing the main thread to block, so the for loop is generally put into the thread for it to run.
Java core programming-thread thread pool (executorservice) (iv)