thread [6] - thread pool

Keywords: Java JDK REST jvm

thread [6] - thread pool

1. Thread pool concept

  • It is a container that contains several threads. Usually a project has only one thread pool. When the program starts, it loads threads. When you need threads, you take threads from the thread pool and process tasks. When you use them, you will not destroy threads. You need to return threads to the thread pool.

  • Thread pools solve the problem of frequently creating threads and destroying threads to occupy resources.

  • Reasonable use of thread pools can bring three benefits:
    1) Reduce resource consumption. Reduce the consumption of thread creation and destruction by reusing created threads.
    2) Improving the response speed. When a task arrives, it can be executed immediately without waiting for the thread to be created.
    3) Improve the manageability of threads. Threads are scarce resources. If created unrestrictedly, it will not only consume system resources, but also reduce the stability of the system. Thread pool can be used for uniform allocation, tuning and monitoring.

  • Before JDK 1.5, developers had to implement their own thread pools manually. After JDK 1.5, Java built-in supports thread pools. All supported classes concurrent with multithreading are in the java.lang.concurrent package, and we can use the classes inside to control the execution of multithreading more.

2. Usually a fixed number of thread pools are used

A fixed number of threads are defined in the thread pool so that memory leaks are not caused by creating too many threads and using too much memory. With a fixed number of thread pools, only a fixed number of threads are run at the same time, and the rest are queued in the thread pool first.

2.1 Relationships among Threads, Tasks and Queues

Thread pools create threads, and there is a queue inside the thread pool (threads in the thread pool are active and unprocessed tasks are queued)

  • Queue: A container for storing tasks

  • Threads: Take tasks from queues for processing

  • Tasks: (At present, all tasks that implement the Runnable interface) are usually defined by us and injected into the thread pool to execute (it may execute immediately, or it may be that the thread is busy and will be queued).

Summary: Thread pool three elements (threads, tasks, queues)

2.2 Create a fixed number of thread pools

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestThreadPool {
	public static void main(String[] args) {
		//Create a fixed data volume thread pool with 10 thread sizes
		//The es compile-time is the interface type, and the run-time is the implementation class ThreadPoolExecutor.
		//ThreadPoolExecutor@7852e922[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
		ExecutorService es = Executors.newFixedThreadPool(10);
		System.out.println("Befor===="+es);
		//Use thread pools to perform tasks (print HelloWorld 100 times)
		for(int i=0;i<100;i++){
			final int index = i;
			//The first execution of a task by a thread pool determines whether there are threads in the pool. If there are no threads, the thread will be created and then the task will be executed.
			es.execute(new Runnable() {
				@Override
				public void run() {			
					System.out.println(index+"\t"+Thread.currentThread().getName()+"::Helloworld");
				}
			});
			//RejectedExecutionException exception is thrown when the thread is stopped inside the loop (task exception is refused)
			//The thread pool has stopped and the task cannot be executed. The JVM throws a Rejected Execution Exception
			//es.shutdown();
		}
		//ThreadPoolExecutor@7852e922[Running, pool size = 10, active threads = 8, queued tasks = 81, completed tasks = 11]
		//The following print statement is not printed until all threads have finished processing tasks, but during processing tasks, because processing tasks takes time.
		//Pool size = thread size in 10 thread pool
		// active threads=8 active threads, 8 threads running (processing tasks)
		//queued tasks = 81 redundant tasks are placed in a queue waiting to be processed. Queue is the meaning of queue, which is understood as warehouse.
		//Complete tasks = 11 processed tasks
		System.out.println("After===="+es);
		//Thread pool stop
		es.shutdown();
	}
}

Posted by danharibo on Mon, 12 Aug 2019 05:08:11 -0700