Home > Java > JavaBase > body text

Java explains ThreadPool thread pool

coldplay.xixi
Release: 2021-03-03 10:36:31
forward
1811 people have browsed it

Java explains ThreadPool thread pool

ThreadPool thread pool

  • 1. Advantages of thread pool
    • ##1.1. Introduction
    • 1.2. Why to use thread pool
  • 2. Use of thread pool
    • 2.1. Architecture description
    • 2.2.Three major methods of thread pool
      • 2.2.1.newFixedThreadPool(int) method
      • 2.2.2.newSingleThreadExector
      • 2.2.3.newCachedThreadPool
  • 3.The underlying principle of ThreadPoolExecutor
  • 4. The seven important parameters of the thread pool
(Related free learning recommendations:

java basic tutorial)

1. Advantages of thread pool

1.1. Introduction

Similar to the database thread pool, if there is no database connection pool, then new is required every time the database connection pool is used to obtain the connection pool. Repeated connection and release operations will consume a lot of system resources. We can use the database connection pool and directly get the connection pool from the pool.

Similarly, before there was a thread pool, we also obtained threads through new Thread.start(). Now we don't need new, so that we can achieve reuse and make our system more efficient.

1.2. Why use thread pool

Example:

    10 years ago single-core CPU computer, fake multi-threading, like The circus clown plays with multiple balls, and the CPU needs to switch back and forth.
  • Now is a multi-core computer. Multiple threads run on independent CPUs, so there is no need to switch and it is highly efficient.

Advantages of the thread pool:

The thread pool only needs to control the number of running threads and put the tasks into the queue during processing. , and then start these tasks after the threads are created. If the number of threads exceeds the maximum number, the excess threads will queue up and wait for other threads to finish executing, and then take the tasks out of the queue for execution.

Its main features are:

  • Thread reuse
  • Control the maximum number of concurrencies
  • Management thread
Advantages:

  • First: Reduce resource consumption. Reduce the overhead caused by thread creation and destruction by reusing already created threads.
  • Second: Improve response speed. When a task arrives, the task can be executed immediately without waiting for thread creation.
  • Third: Improve the manageability of threads. Threads are scarce resources. If they are created without restrictions, they will not only consume system resources, but also reduce the stability of the system. The thread pool can be used for unified allocation, tuning and monitoring.

2. Use of thread pool

2.1. Architecture description

Executor What is a framework?

This is how it is described in Java Doc

An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads.

Object that executes submitted Runnable tasks. This interface provides a mechanism to submit tasks and how to run each task, including details of thread usage, scheduling, etc. It is common to use an Executor instead of explicitly creating threads.

The thread pool in Java is implemented through the Executor framework, which uses the classes Executor, Executors, ExecutorService, and ThreadPoolExecutor.

The interface we commonly use is the ExecutorService sub-interface, Executors are tool classes for threads (tool classes similar to arrays Arrays, tool classes Collections for collections). ThreadPoolExecutor is the focus of these classes. We can get the ThreadPoolExecutor thread pool through the auxiliary tool class Executors
Java explains ThreadPool thread pool A more detailed introduction to each class is as follows:

Executor interfaces for all thread pools , there is only one method. This interface defines the way to execute Runnable tasks
ExecutorService adds the behavior of Executor, which is the most direct interface of Executor implementation class. This interface definition provides services for Executor
Executors thread pool factory class provides a series of factory methods for creating thread pools. The returned thread pools all implement ScheduledExecutorService: scheduled scheduling interface.
AbstractExecutorService execution framework abstract class.

ThreadPoolExecutor The specific implementation of the thread pool in JDK. Various commonly used thread pools are implemented based on this class.

2.2. Three major methods of thread pool

2.2.1.newFixedThreadPool(int) method

Exectors.newFixedThreadPool(int) -->

Good performance in executing long-term tasks, create a Thread pool, a pool has N fixed threads, and a fixed number of threads

	public static void main(String[] args) {
		//一池5个受理线程,类似一个银行5个受理窗口。不管你现在多少个线程,都只有5个
		ExecutorService threadPool=Executors.newFixedThreadPool(5); 
		
		try {
			//模拟有10个顾客过来银行办理业务,目前池子里面有5个工作人员提供服务。
			for(int i=1;i{
					System.out.println(Thread.currentThread().getName()+"\t 办理业务");
				});
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			threadPool.shutdown();
		}	
	}
Copy after login

Java explains ThreadPool thread pool
You can see the execution results. There are 5 threads in the pool, which is equivalent to 5 staff members providing external services and handling business. In the picture, window No. 1 handles business twice, and the bank's acceptance window can be reused multiple times. It’s not necessarily that everyone handles it twice, but whoever handles it faster will handle more.

When we add a 400ms delay during thread execution, we can see the effect

public static void main(String[] args) {
		//一池5个受理线程,类似一个银行5个受理窗口。不管你现在多少个线程,都只有5个
		ExecutorService threadPool=Executors.newFixedThreadPool(5); 
		
		try {
			//模拟有10个顾客过来银行办理业务,目前池子里面有5个工作人员提供服务。
			for(int i=1;i{
					System.out.println(Thread.currentThread().getName()+"\t 办理业务");
				});
				try {
					TimeUnit.MILLISECONDS.sleep(400);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			threadPool.shutdown();
		}	
	}
Copy after login

Java explains ThreadPool thread pool
This means that the network is congested or the business is relatively slow. Then the distribution of business tasks handled by the thread pool is relatively even.

2.2.2.newSingleThreadExector

Exectors.newSingleThreadExector()–>Execution of one task, one pool, one thread

public static void main(String[] args) {
	//一池一个工作线程,类似一个银行有1个受理窗口
	ExecutorService threadPool=Executors.newSingleThreadExecutor(); 	
	try {
		//模拟有10个顾客过来银行办理业务
		for(int i=1;i{
				System.out.println(Thread.currentThread().getName()+"\t 办理业务");
			});
		}
	} catch (Exception e) {
		// TODO: handle exception
	}finally{
		threadPool.shutdown();
	}	}
Copy after login

Java explains ThreadPool thread pool

2.2.3.newCachedThreadPool

Exectors.newCachedThreadPool()–>Perform many short-term asynchronous tasks. The thread pool creates new threads as needed, but in the previously constructed threads They will be reused when available. It can be expanded, and it will be strong when it is strong. A pool of n threads, expandable, scalable, cache cache means
So how much should the number of pools be set? If the bank has only one window, then when too many people come, it will be too busy. If a bank has many windows but few people come, it will seem like a waste of resources. So how to make reasonable arrangements? This requires the use of the newCachedThreadPool() method, which is expandable and scalable

public static void main(String[] args) {
		//一池一个工作线程,类似一个银行有n个受理窗口
		ExecutorService threadPool=Executors.newCachedThreadPool(); 	
		try {
			//模拟有10个顾客过来银行办理业务
			for(int i=1;i{
					System.out.println(Thread.currentThread().getName()+"\t 办理业务");
				});
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			threadPool.shutdown();
		}	
	}
Copy after login
Copy after login

Java explains ThreadPool thread pool

public static void main(String[] args) {
		//一池一个工作线程,类似一个银行有n个受理窗口
		ExecutorService threadPool=Executors.newCachedThreadPool(); 	
		try {
			//模拟有10个顾客过来银行办理业务
			for(int i=1;i{
					System.out.println(Thread.currentThread().getName()+"\t 办理业务");
				});
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			threadPool.shutdown();
		}	
	}
Copy after login
Copy after login

Java explains ThreadPool thread pool

3. The underlying principle of ThreadPoolExecutor

newFixedThreadPool underlying source code

 public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<runnable>());
    }</runnable>
Copy after login

As you can see, the underlying parameters include LinkedBlockingQueue blocking queue.

newSingleThreadExecutor underlying source code

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<runnable>()));
    }</runnable>
Copy after login

newCachedThreadPool underlying source code

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<runnable>());
    }</runnable>
Copy after login

SynchronousQueue This blocking queue is a single version of the blocking queue, and the blocking queue has a capacity of 1.

These three methods actually all return an object, which is the object of ThreadPoolExecutor.

4. The seven important parameters of the thread pool

Constructor of ThreadPoolExecutor

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize <p>The above int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit , BlockingQueue workQueue, ThreadFactory threadFactory, <br> RejectedExecutionHandler handler is our seven thread parameters <br> The above is the construction method of the ThreadPoolExecutor class, with seven parameters: </p>
<p>1) <strong>corePoolSize: thread pool The number of resident core threads in </strong>, referred to as the number of cores. <br> For example, we can treat a thread pool as a bank branch. As long as the bank opens its doors, there must be at least one person on duty. This is called the number of resident core threads. For example, if a bank has all five branches open from Monday to Friday, then the number of resident core threads from Monday to Friday is 5. If business is not that frequent today and the window is 1, then the number of resident core threads today is 1 </p>
<p>2) <strong>maxImumPoolSize: The maximum number of threads that can be executed simultaneously in the thread pool. This value must be greater than or equal to 1</strong></p>
<p>3) <strong>keepAliveTime: excess idle time The survival time of threads. When the number of threads in the current pool exceeds corePoolSize, when the idle time reaches keepAliveTime, the excess threads will be destroyed until corePoolSize is left. </strong><br> If there are resident threads in the thread pool, and there is a maximum The number of threads means that it is usually resident. If the work is tense, it will be expanded to the maximum number of threads. If the business drops, we set the survival time of the excess idle threads, such as setting it to 30s. If there is no excess for 30s, When you request it, some banks close the window, so it not only expands but also shrinks. </p>
<p>4) <strong>unit: unit of keepAliveTime</strong><br> Unit: seconds, milliseconds, microseconds. </p>
<p><strong>5) workQueue: task queue, tasks that have been submitted but have not been executed </strong><br> This is a blocking queue, such as a bank, which only has 3 acceptance windows, and 4 are coming. customers. This blocking queue is the waiting area of ​​the bank. Once a customer comes, he cannot be allowed to leave. The number of windows controls the number of concurrent threads. </p>
<p>6) <strong>threadFactory: Represents the thread factory that generates working threads in the thread pool. It is used to create threads. Generally, the default is </strong><br>. Threads are all created uniformly. There are new threads in the thread pool, which are produced by the thread pool factory. </p>
<p><strong>7) handler: rejection strategy, indicating how to reject the runnable request execution strategy when the current queue is full and the working thread is greater than or equal to the maximum number of threads in the thread pool (maximumPoolSize)</strong></p>
<p>For example, today is the peak customer flow at the bank. All three windows are full and the waiting area is also full. We did not choose to continue recruiting people because it was not safe, so we chose to politely refuse. </p>
<p>In the next section we will introduce the underlying working principle of the thread pool</p>
<blockquote><p><strong>Related learning recommendations: </strong><a href="//m.sbmmt.com/java/base/" target="_blank"><strong>java basics</strong></a> </p></blockquote></runnable>
Copy after login

The above is the detailed content of Java explains ThreadPool thread pool. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!