Thread Pool
A container that holds multiple threads, in which the threads can be used repeatedly without the frequent creation of thread objects, so as not to consume too many resources.
Why use thread pools? In java, if each request arrives to create a new thread, the overhead is quite large, including the consumption of time and computer resources. If too many threads are created in a jvm, it may cause the system to run out of system resources due to excessive memory consumption or "overswitching". In order to prevent shortage of resources, it is necessary to take some measures to limit the number of requests processed at any given time, to reduce the number of threads created and destroyed as much as possible, especially the creation and destruction of some threads with high resource consumption, try to use existing objects to service. The thread pool is mainly used to solve the problem of thread life cycle overhead and insufficient resources. By reusing threads for multiple tasks, the overhead of thread creation is amortized over multiple tasks, and since the thread already exists by the time the request arrives, the delay introduced by thread creation is eliminated. This way, the request can be serviced immediately, with a faster response from the application. In addition, resource shortage can be prevented by properly adjusting the number of threads in the thread.
One of the ways to use the process pool - the Runnable interface:
Usually, the thread pool is created through the thread pool factory, then calls the method in the thread pool to obtain the thread, and then executes the task method through the thread.
Executors: Thread pool creation factory class
Method public static ExecutorService newFixedThreadPool(int nThreads): Returns the thread pool object
ExecutorService: thread pool class
Future<?> submit(Runnable task): Get a thread object in the thread pool and execute it
Note: The Future interface is used to record the result generated after the thread task is executed.
Steps to use thread objects in the thread pool:
1. Create a thread pool object
2. Create a subclass object of the Runnable interface
3. Submit the Runnable interface subclass object
4. Close the thread pool
Code demo:
//ThreadPoolDemo.java public class ThreadPoolDemo { public static void main(String[] args) { // Create thread pool object ExecutorService service = Executors.newFixedThreadPool(2); // Contain 2 thread objects // Create Runnable instance object MyRunnable r = new MyRunnable( ); // The way to create a thread object by yourself // Thread t = new Thread(r); // t.start(); ---> call run() in MyRunnable // Get the thread object from the thread pool, then call run() in MyRunnable service.submit(r); // Get another thread object and automatically call run() in MyRunnable service.submit(r); service.submit(r); // Note: After the submit method is called, the program does not terminate because the thread pool controls the shutdown of the thread. Return the used thread to the thread pool // Close the thread pool // service.shutdown(); } } class MyRunnable implements Runnable { @Override public void run() { System.out.println("run"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace (); } System.out.println("threadname: " +Thread.currentThread().getName()); System.out.println("end..."); } }
The second method of using the thread pool - the Callable interface
The Callable interface is similar in function to the Runnable interface and is used for tasks that specify a thread. The call() method is used to return the result after the thread task is executed (call() can throw an exception).
ExecutorService: thread pool class
Future<T> submit(Callable<T> task): Get a thread object in the thread pool and execute the call() method in the thread.
Steps to use thread objects in the thread pool:
1. Create a thread pool object
2. Create a subclass object of the Callable interface
3. Submit the Callable interface subclass object
4. Close the thread pool
Code demo:
//ThreadPoolDemo.java public class ThreadPoolDemo { public static void main(String[] args) { // Create a thread pool object ExecutorService service = Executors.newFixedThreadPool(2); // Contain 2 thread objects // Create a Callable object MyCallable c = new MyCallable() ; // Get the thread object from the thread pool, and then call run() in MyRunnable service.submit(c); service.submit(c); service.submit(c); // Note: After the submit method is called, the program does not terminate because the thread pool controls the shutdown of the thread. Return the used thread to the thread pool // Close the thread pool // service.shutdown(); } } class MyCallable implements Callable { @Override public Object call() throws Exception { System.out.println("run:call"); Thread.sleep(2000); System.out.println("threadname: " +Thread.currentThread().getName()); System.out.println("end"); return null; } }