当前位置:网站首页>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
边栏推荐
- ~89 deformation translation
- Lv166 turned over
- The content of the source code crawled by the crawler is inconsistent with that in the developer mode
- Socks agent tools earthworm, ssoks
- FIREBIRD使用经验总结
- 2021 Google vulnerability reward program review
- Selenium browser (2)
- Salient map drawing based on OpenCV
- 《吐血整理》保姆级系列教程-玩转Fiddler抓包教程(2)-初识Fiddler让你理性认识一下
- Some fields of the crawler that should be output in Chinese are output as none
猜你喜欢
How was MP3 born?
@EnableAspectAutoJAutoProxy_ Exposeproxy property
[North Asia data recovery] data recovery case of database data loss caused by HP DL380 server RAID disk failure
[hcie TAC] question 5 - 1
Communication mode based on stm32f1 single chip microcomputer
AutoCAD - set color
Interface fonctionnelle, référence de méthode, Widget de tri de liste implémenté par lambda
Statistical learning: logistic regression and cross entropy loss (pytoch Implementation)
Principle and general steps of SQL injection
Model fusion -- stacking principle and Implementation
随机推荐
Change the mouse pointer on ngclick - change the mouse pointer on ngclick
Accounting regulations and professional ethics [6]
Move, say goodbye to the past again
@EnableAspectAutoJAutoProxy_ Exposeproxy property
Accounting regulations and professional ethics [8]
Selenium browser (2)
Practice: fabric user certificate revocation operation process
Market trend report, technical innovation and market forecast of China's hair repair therapeutic apparatus
Application and Optimization Practice of redis in vivo push platform
Ten clothing stores have nine losses. A little change will make you buy every day
ECCV 2022放榜了:1629篇论文中选,录用率不到20%
Research Report on plastic recycling machine industry - market status analysis and development prospect forecast
Object.keys()的用法
Hair growth shampoo industry Research Report - market status analysis and development prospect forecast
多年锤炼,迈向Kata 3.0 !走进开箱即用的安全容器体验之旅| 龙蜥技术
QT graphical view frame: element movement
Market trend report, technical innovation and market forecast of taillight components in China
Research Report on market supply and demand and strategy of tetramethylpyrazine industry in China
Redis' optimistic lock and pessimistic lock for solving transaction conflicts
话里话外:流程图绘制初级:六大常见错误