当前位置:网站首页>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
边栏推荐
- Market trend report, technical innovation and market forecast of China's hair repair therapeutic apparatus
- .Net 应用考虑x64生成
- Application of clock wheel in RPC
- Market trend report, technical innovation and market forecast of electrochromic glass and devices in China and Indonesia
- Recommend 10 excellent mongodb GUI tools
- Web components series - detailed slides
- Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"
- Accounting regulations and professional ethics [6]
- Common knowledge of unity Editor Extension
- Research Report on market supply and demand and strategy of China's plastics and polymer industry
猜你喜欢
Communication mode based on stm32f1 single chip microcomputer
对人胜率84%,DeepMind AI首次在西洋陆军棋中达到人类专家水平
DC-2靶场搭建及渗透实战详细过程(DC靶场系列)
Overview of convolutional neural network structure optimization
Opencv learning -- geometric transformation of image processing
Filtered off site request to
Transformer中position encoding实践
Vscode setting outline shortcut keys to improve efficiency
Actual combat | use composite material 3 in application
Statistical learning: logistic regression and cross entropy loss (pytoch Implementation)
随机推荐
[North Asia data recovery] a database data recovery case where the disk on which the database is located is unrecognized due to the RAID disk failure of HP DL380 server
同构图与异构图CYPHER-TASK设计与TASK锁机制
Lv166 turned over
Research Report on market supply and demand and strategy of China's well completion equipment industry
Market trend report, technical innovation and market forecast of China's hair repair therapeutic apparatus
@EnableAspectAutoJAutoProxy_ Exposeproxy property
Principle and general steps of SQL injection
Actual combat | use composite material 3 in application
How to decrypt worksheet protection password in Excel file
DC-2靶场搭建及渗透实战详细过程(DC靶场系列)
error: ‘connect‘ was not declared in this scope connect(timer, SIGNAL(timeout()), this, SLOT(up
Accounting regulations and professional ethics [9]
How to save the contents of div as an image- How to save the contents of a div as a image?
The four most common errors when using pytorch
Sql实现Split
Daily notes~
Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"
基于check-point实现图数据构建任务
Intranet penetrating FRP: hidden communication tunnel technology
Principle and general steps of SQL injection