当前位置:网站首页>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
边栏推荐
- Explore mongodb - mongodb compass installation, configuration and usage introduction | mongodb GUI
- Hair growth shampoo industry Research Report - market status analysis and development prospect forecast
- 话里话外:流程图绘制初级:六大常见错误
- Model fusion -- stacking principle and Implementation
- Recommend 10 excellent mongodb GUI tools
- Audio and video technology development weekly | 252
- std::shared_ ptr initialization: make_ shared&lt; Foo&gt; () vs shared_ ptr&lt; T&gt; (new Foo) [duplicate]
- Working group and domain analysis of Intranet
- 基于check-point机制的任务状态回滚和数据分块任务
- .Net 应用考虑x64生成
猜你喜欢
Intranet penetrating FRP: hidden communication tunnel technology
Using celery in projects
AutoCAD - set color
How to decrypt worksheet protection password in Excel file
Big God explains open source buff gain strategy live broadcast
D3D11_ Chili_ Tutorial (2): draw a triangle
Object.keys()的用法
对人胜率84%,DeepMind AI首次在西洋陆军棋中达到人类专家水平
[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
Model fusion -- stacking principle and Implementation
随机推荐
ECCV 2022放榜了:1629篇论文中选,录用率不到20%
Talking about Net core how to use efcore to inject multiple instances of a context annotation type for connecting to the master-slave database
Daily notes~
Cut! 39 year old Ali P9, saved 150million
[Previous line repeated 995 more times]RecursionError: maximum recursion depth exceeded
System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
Qt---error: ‘QObject‘ is an ambiguous base of ‘MyView‘
China Indonesia adhesive market trend report, technological innovation and market forecast
D3D11_ Chili_ Tutorial (2): draw a triangle
Some fields of the crawler that should be output in Chinese are output as none
Proxifier global agent software, which provides cross platform port forwarding and agent functions
Summary of database 2
Feature extraction and detection 15-akaze local matching
Hair growth shampoo industry Research Report - market status analysis and development prospect forecast
时序图数据建模与产业链分析
How can floating point numbers be compared with 0?
~89 deformation translation
MFC implementation of ACM basic questions encoded by the number of characters
Accounting regulations and professional ethics [7]
FIREBIRD使用经验总结