当前位置:网站首页>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
边栏推荐
- Understand asp Net core - Authentication Based on jwtbearer
- Research Report on market supply and demand and strategy of China's well completion equipment industry
- 同构图与异构图CYPHER-TASK设计与TASK锁机制
- Qt---error: ‘QObject‘ is an ambiguous base of ‘MyView‘
- Talking about Net core how to use efcore to inject multiple instances of a context annotation type for connecting to the master-slave database
- What is torch NN?
- The new generation of domestic ORM framework sagacity sqltoy-5.1.25 release
- 程序员怎么才能提高代码编写速度?
- c# 实现定义一套中间SQL可以跨库执行的SQL语句
- FIREBIRD使用经验总结
猜你喜欢

Position encoding practice in transformer

The 17 year growth route of Zhang Liang, an open source person, can only be adhered to if he loves it

What is torch NN?
![[Previous line repeated 995 more times]RecursionError: maximum recursion depth exceeded](/img/c5/f933ad4a7bc903f15beede62c6d86f.jpg)
[Previous line repeated 995 more times]RecursionError: maximum recursion depth exceeded
![[North Asia data recovery] a database data recovery case where the partition where the database is located is unrecognized due to the RAID disk failure of HP DL380 server](/img/21/513042008483cf21fc66729ae1d41f.jpg)
[North Asia data recovery] a database data recovery case where the partition where the database is located is unrecognized due to the RAID disk failure of HP DL380 server
![[hcie TAC] question 5 - 1](/img/e0/1b546de7628695ebed422ae57942e4.jpg)
[hcie TAC] question 5 - 1

error: ‘connect‘ was not declared in this scope connect(timer, SIGNAL(timeout()), this, SLOT(up

~88 running people practice

A trap used by combinelatest and a debouncetime based solution

Transformer中position encoding实践
随机推荐
Opencv learning -- arithmetic operation of image of basic operation
@EnableAspectAutoJAutoProxy_ Exposeproxy property
Model fusion -- stacking principle and Implementation
同构图与异构图CYPHER-TASK设计与TASK锁机制
Feature extraction and detection 15-akaze local matching
AI system content recommendation issue 24
Common knowledge of unity Editor Extension
高度剩余法
实战:fabric 用户证书吊销操作流程
China's plastic processing machinery market trend report, technological innovation and market forecast
Market trend report, technical innovation and market forecast of taillight components in China
Vscode setting outline shortcut keys to improve efficiency
Object distance measurement of stereo vision
跳跃表实例
Big God explains open source buff gain strategy live broadcast
D3D11_ Chili_ Tutorial (2): draw a triangle
China Indonesia adhesive market trend report, technological innovation and market forecast
The new generation of domestic ORM framework sagacity sqltoy-5.1.25 release
How to save the contents of div as an image- How to save the contents of a div as a image?
What is torch NN?