当前位置:网站首页>Use and principle of thread pool
Use and principle of thread pool
2022-07-04 16:41:00 【Full stack programmer webmaster】
Catalog
One 、 Role of thread pool
Two 、 Diagram of thread pool
3、 ... and 、 Creation and parameters of thread pool
Four 、 How thread pools work
5、 ... and 、 The use of thread pools
One 、 Role of thread pool
With cpu More and more cores , Inevitably, multithreading technology is used to make full use of its computing power . therefore , Multithreading technology is a technology that service developers must master . Thread creation and destruction , All involve system calls , It consumes system resources , Therefore, the line process pool technology is introduced , There are already created threads in the thread pool , Can be used directly , And used up , Directly put it back into the process pool again , Avoid frequent thread creation and destruction .
Two 、 Diagram of key classes of thread pool
As can be seen from the above Java There are two main implementation classes of thread pool ThreadPoolExecutor and ForkJoinPool.
ForkJoinPool yes Fork/Join A thread pool used under the framework , In general , What we use more is ThreadPoolExecutor. Most of the time, we create thread pools through Executors
3、 ... and 、 Thread pool creation and parameter resolution
Let's first look at the construction method of creating a thread pool with the most complete parameters
Argument parsing :
①corePoolSize: Number of core threads in thread pool , To put it bluntly , Even if there are no tasks in the thread pool , There will be corePoolSize A thread is waiting for the task .
②maximumPoolSize: Maximum number of threads , No matter how many tasks you submit , The maximum number of working threads in the thread pool is maximumPoolSize.
③keepAliveTime: Thread lifetime . When the number of threads in the thread pool is greater than corePoolSize when , If you wait keepAliveTime There are no tasks to perform for a long time , The thread exits .
⑤unit: This is used to specify keepAliveTime The unit of , Like seconds :TimeUnit.SECONDS.
⑥workQueue: A blocking queue , The submitted task will be placed in this queue .
⑦threadFactory: Thread factory , Used to create threads , Mainly to name the thread , The thread name of the default factory :pool-1-thread-3.
⑧handler: Refusal strategy , When the thread pool is exhausted , And when the queue is full, it will call .
Thread pool creation :
java.util.concurrent.Executosr Is a static factory for thread pools , We usually use it to easily produce various types of thread pools , There are four main methods :
1、newSingleThreadExecutor()—— Create a single-threaded thread pool
2、newFixedThreadPool(int n)—— Create a fixed-size thread pool
3、newCachedThreadPool()—— Create a cacheable thread pool
4、newScheduledThreadPool()—— Create a thread pool with a fixed number of threads , Support regular and periodic execution of background tasks .
(1)newSingleThreadExecutor() Thread pool for single thread count
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
The key is corePoolSize( Number of core threads ) Parameters and maximumPoolSize( Maximum number of threads ) Both parameters are 1
(2)newFixedThreadPool() Thread pool with fixed number of threads
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
It can be seen that corePoolSize( Number of core threads ) Parameters and maximumPoolSize( Maximum number of threads ) Both parameters are equal
(3)newCachedThreadPool() Create a thread pool that can create new threads as needed , It has no limit on the number of threads
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
corePoolSize=0,maximumPoolSize=Integer.MAX_VALUE( Think it's infinite )keepAliveTime=60s, When 60s Seconds later, the thread without task execution will exit , because CachedThreadPool The thread is not online , Wireless thread creation requires a lot of memory , It needs to be used with caution
(4)newScheduledThreadPool(): Create a thread pool with a fixed number of threads , Support regular and periodic execution of background tasks . This one is less used , Just skip
Four 、 How thread pools work
Use a diagram to describe the process of thread pool execution
The figure corresponds to the following source code :
5、 ... and 、 Thread pool usage
example
(1)newSingleThreadExecutor
MyThread.java
public class MyThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName() + " Being implemented ...");
}
}
ThreadPoolTest.java
ThreadPoolTest.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolTest {
public static void main(String[] args) {
// Create a thread pool that can reuse a fixed number of threads
ExecutorService pool = Executors. newSingleThreadExecutor();
// Created and implemented Runnable Interface object ,Thread Of course, the object also realizes Runnable Interface
Thread t1 = new MyThread();
Thread t2 = new MyThread();
Thread t3 = new MyThread();
Thread t4 = new MyThread();
Thread t5 = new MyThread();
// Put the thread into the pool for execution
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
// Close thread pool
pool.shutdown();
}
}
Running results :
(2)newFixedThreadPool
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolTest {
public static void main(String[] args) {
// Create a thread pool that can reuse a fixed number of threads
//ExecutorService pool = Executors. newSingleThreadExecutor();
// Fixed thread pool size
ExecutorService pool = Executors.newFixedThreadPool(2);
// Created and implemented Runnable Interface object ,Thread Of course, the object also realizes Runnable Interface
Thread t1 = new MyThread();
Thread t2 = new MyThread();
Thread t3 = new MyThread();
Thread t4 = new MyThread();
Thread t5 = new MyThread();
// Put the thread into the pool for execution
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
// Close thread pool
pool.shutdown();
}
}
Running results :
(3)newCachedThreadPool
According to the above , Just modify one sentence
// Create a thread pool that can reuse a fixed number of threads
ExecutorService pool = Executors.newCachedThreadPool();
Running results :
Okay , Let's stop here for a brief introduction to thread pool , If there is any wrong , Your advice are most welcome .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/111249.html Link to the original text :https://javaforall.cn
边栏推荐
- Detailed process of DC-2 range construction and penetration practice (DC range Series)
- Opencv learning -- arithmetic operation of image of basic operation
- 函數式接口,方法引用,Lambda實現的List集合排序小工具
- [hcie TAC] question 5 - 1
- Redis: SDS source code analysis
- [Chongqing Guangdong education] National Open University spring 2019 1248 public sector human resource management reference questions
- Hidden communication tunnel technology: intranet penetration tool NPS
- 如何为ONgDB核心项目源码做贡献
- Feature extraction and detection 15-akaze local matching
- c# 实现定义一套中间SQL可以跨库执行的SQL语句
猜你喜欢
Penetration test --- database security: detailed explanation of SQL injection into database principle
Vscode setting outline shortcut keys to improve efficiency
嵌入式软件架构设计-函数调用
科普达人丨一文看懂阿里云的秘密武器“神龙架构”
Redis' optimistic lock and pessimistic lock for solving transaction conflicts
Principle and general steps of SQL injection
一图看懂ThreadLocal
Position encoding practice in transformer
Working group and domain analysis of Intranet
AI system content recommendation issue 24
随机推荐
%F format character
Change the mouse pointer on ngclick - change the mouse pointer on ngclick
线程池的使用和原理
How to decrypt worksheet protection password in Excel file
Cut! 39 year old Ali P9, saved 150million
ECCV 2022放榜了:1629篇论文中选,录用率不到20%
Digital recognition system based on OpenCV
Accounting regulations and professional ethics [11]
[Chongqing Guangdong education] National Open University spring 2019 1248 public sector human resource management reference questions
Market trend report, technical innovation and market forecast of China's hair repair therapeutic apparatus
[Chongqing Guangdong education] National Open University spring 2019 1396 pharmaceutical administration and regulations (version) reference questions
CMPSC311 Linear Device
Object.keys()的用法
Rearrange array
Big God explains open source buff gain strategy live broadcast
如何为ONgDB核心项目源码做贡献
Overview of convolutional neural network structure optimization
China tall oil fatty acid market trend report, technical dynamic innovation and market forecast
Laravel simply realizes Alibaba cloud storage + Baidu AI Cloud image review
Research Report on plastic recycling machine industry - market status analysis and development prospect forecast