当前位置:网站首页>Concurrent programming - thread pool
Concurrent programming - thread pool
2022-06-22 04:51:00 【v_ BinWei_ v】
Concurrent programming —— Thread pool
1、 Introduction to thread pool
Creating a thread is very easy , But if the number of concurrent threads is large , And each thread executes a short task and ends , This frequent thread creation can greatly reduce the efficiency of the system , Because it takes time to create and destroy threads frequently . To solve such problems ,Java Proposed the solution of thread pool . The thread pool is actually a container for storing threads . When calling the thread pool to execute concurrent tasks , Take the thread from the thread pool to execute the task , Every thread Finish the task , Not destroyed , Instead, it is recycled by the thread pool , Continue task next time .
There are two ways to create a thread pool first , The first is to use Executors Framework tool class Create various types of thread pools for classes , The second is direct **new ThreadPoolExecutor()** Thread pool of , The parameters in the middle are defined by themselves , Each method has its own advantages and disadvantages .
2、 How to create thread pool
2.1、Executors Framework creates a thread pool
EXecutors Use the factory pattern to create four types of ThreadPoolExecutor Thread pool
- FixedThreadPool : This method returns a thread pool with a fixed number of threads . The number of threads in this thread pool is always the same . When a new task is submitted , If there are idle threads in the thread pool , Immediately . If there is no , The new task will be stored in a task queue , When a thread is free , Then I will process the tasks in the task queue .
- SingleThreadExecutor: Method returns a thread pool with only one thread . If more than one task is submitted to the thread pool , The task will be saved in a task queue , Wait for the thread to be idle , Perform tasks in the queue in first in first out order .
- CachedThreadPool: This method returns a thread pool that can adjust the number of threads according to the actual situation . The number of threads in the thread pool is uncertain , But if there are idle threads to reuse , Then the reusable threads will be preferred . If all threads are working , There are new tasks to submit , A new thread processing task will be created . After all threads have finished executing the current task , Will return to the thread pool for reuse .
- ScheduledExecutorService You can implement looping or deferred tasks When it comes to delaying and looping tasks
Specific creation method
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
ExecutorService fixedFhreadPool = Executors.newFixedThreadPool();
Executors.newScheduledThreadPool();
Source code analysis
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-AwCjFsRH-1655536900843)(F:\ Xidian graduate student \ Resume of senior students \ Project experience summary .assets\image-20220506190204993.png)]](/img/24/cbf6a48bed91e98225d435d1d01012.png)
Executor
Executor Is a top-level interface , There is only one method declared in it execute(Runnable), The return value is void, Parameter is Runnable type , It can be understood literally , It's used to perform the task transferred in .
ExecutorService
ExecutorService Interface inherited Executor Interface , And declared some methods :submit、invokeAll、invokeAny as well as shutDown Other methods .
exectue() and submit() The difference between
1. **`execute()` Method is used to submit tasks that do not require a return value , Therefore, it is impossible to judge whether the task is successfully executed by the thread pool ;**
2. **`submit()` Method is used to submit tasks that require a return value . The thread pool will return a `Future` Object of type , Through this `Future` Object can determine whether the task is executed successfully **, And through `Future` Of `get()` Method to get the return value ,`get()` Method blocks the current thread until the task is completed , While using `get(long timeout,TimeUnit unit)` Method will block the current thread for a period of time and return to , At this time, it is possible that the task is not finished .
AbstractExecutorService
abstract class AbstractExecutorService Realized ExecutorService Interface , Basically achieved ExecutorService All methods declared in ;
ThreadPoolExecutor
ThreadPoolExecutor Inherited classes AbstractExecutorService.
2.2 Use it directly ThreadPoolExecutor Creating a thread pool
Use ThreadPoolExecutor It mainly configures the corresponding parameters
/* Creates a new ThreadPoolExecutor with the given initial parameters. Params: corePoolSize – the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set maximumPoolSize – the maximum number of threads to allow in the pool keepAliveTime – when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. unit – the time unit for the keepAliveTime argument workQueue – the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method. threadFactory – the factory to use when the executor creates a new thread handler – the handler to use when execution is blocked because the thread bounds and queue capacities are reached Throws: IllegalArgumentException – if one of the following holds: corePoolSize < 0 keepAliveTime < 0 maximumPoolSize <= 0 maximumPoolSize < corePoolSize NullPointerException – if workQueue or threadFactory or handler is null */
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
Parameters, :
corePoolSize: Indicates the number of threads kept in the thread , Even if these threads are idle , And always
maximumPoolSize: The maximum number of threads that can be held in the thread pool
keepAliveTime: When the number of threads is greater than the kernel , This is the maximum time that redundant idle threads can wait for new tasks before terminating .
unit: Time unit ,TimeUnit.SECONDS、TimeUnit.HOURS…
workQueue: Queue used to save tasks before executing them . This queue will only be saved by execute Method to submit a runnable task
threadFactory: The factory to be used when executing the program to create a new thread
handler: The handler to be used when execution is blocked due to reaching the thread boundary and queue capacity
RejectedExecutionHandler Refusal strategy :
AbortPolicy: This policy is the default policy of thread pool . When using this policy , If the thread pool queue is full, drop the task and throw the RejectedExecutionException abnormal .
DiscardPolicy: This strategy is similar to AbortPolicy Of slient edition , If the thread pool queue is full , It's going to lose the mission and there won't be any exceptions .
DiscardOldestPolicy: This strategy is also well understood literally , Discard the oldest . That is, if the queue is full , The tasks that enter the queue first will be deleted to make room , Try to join the queue again . Because the queue is at the end of the queue , Team leader , So the team leader element is the oldest , So every time you remove the opponent element and then try to join the team .
CallerRunsPolicy: Use this policy , If adding to the thread pool fails , Then the main thread will execute the task itself , Does not wait for threads in the thread pool to execute . Like a quick tempered man , I can't wait for others to do it, so I'll just do it myself .
Customize : Custom reject content and methods
Test reject policy code
class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
try {
System.out.println(this.name + " is running.");
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Creating a thread pool . Thread pool " Maximum pool size " and " Core pool size " All for 1(THREADS_SIZE)," Thread pool " The blocking queue capacity of is 1(CAPACITY).
ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(1));
// Set the rejection policy of thread pool to " discarded "
pool.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
// newly build 10 A mission , And add them to the thread pool .
for (int i = 0; i < 10; i++) {
Runnable myrun = new MyRunnable("task-"+i);
pool.submit(myrun);
}
// Close thread pool
pool.shutdown();
Output results 
3、 Development rules for concurrent programming
1、 To obtain singleton object, thread safety should be guaranteed , Among them, methods should also ensure thread safety .
2、 Specify a meaningful thread name when creating a thread or thread pool , Facilitate backtracking in case of error .
3、 Thread resources must be provided through the thread pool , It is not allowed to explicitly create threads in the application .
4、 Thread pools are not allowed Executors To create , But through ThreadPoolExecutor The way , such To make the rules of the thread pool more explicit , Avoid the risk of resource depletion . Therefore, the second method of creating threads is recommended
explain :Executors The disadvantages of the returned thread pool object are as follows :
1)FixedThreadPool and SingleThreadPool: The allowed request queue length is Integer.MAX_VALUE, A large number of requests may pile up , Which leads to OOM.
2)CachedThreadPool and ScheduledThreadPool: The number of threads allowed to be created is Integer.MAX_VALUE, A large number of threads may be created , Which leads to OOM.
边栏推荐
- requests cookie更新值
- Go learning (II. Built in container)
- "O & M youxiaodeng" active directory batch modification user
- Researcher of Shangtang intelligent medical team interprets organ image processing under intelligent medical treatment
- Solutions to MySQL 8.0 public key retrieval is not allowed errors
- 系统整理|这个模型开发前的重要步骤有多少童鞋忘记细心做好(实操)
- 第6章无穷级数_傅立叶级数
- How much does it cost to buy a fixed-term life insurance with an insured amount of 500000 at the age of 42? Is there any product recommendation
- 【故障诊断】使用多线程,程序不报错,但就是不运行
- NFT mall building digital collection mall building digital collection market digital collection development company
猜你喜欢

Solutions to MySQL 8.0 public key retrieval is not allowed errors

【科研笔记】Focal Loss

Get the specified row content in Oracle rownum and row_ number()

Exness: ECB president Christine Lagarde reiterated her plan to raise interest rates at the July meeting

下拉刷新,上推加载(简单好用,终于会了)

【故障诊断】stitch.py脚本失效

爬梯子&&卖卖股份的最佳时期(跑路人笔记)

Progress information collection for progress control of Zhiyuan project management SPM system

Golang為什麼不推薦使用this/self/me/that/_this

Web design and production final assignment report -- animator Hayao Miyazaki
随机推荐
On the income of enterprise executives
Requests cookie update value
使用matplotlib实现GUI交互效果
使用Echart绘制3D饼环图、仪表盘、电池图
轻量级CNN设计技巧
Cloud function realizes fuzzy search function
Systematic arrangement | how many children's shoes have forgotten to be done carefully before the model development (practical operation)
Learning signal integrity from scratch -- 7-si analysis and simulation
Mongo fuzzy query, with special characters that need to be escaped, and then query
slurm 使用教程
浏览器--常用的搜索操作符大全--使用/实例
Overrides vs overloads of methods
【故障诊断】CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace b
Daemon flow
About SSM integration, this is enough ~ (nanny level hands-on tutorial)
mysql常用sql
Progress warning and problem management of progress control in Zhiyuan project management SPM system
A domestic developer opened the "programmer's Guide to cooking" and became popular!
Golang為什麼不推薦使用this/self/me/that/_this
Thinkphp 的sesssion在同一个控制器不同的方法无法获取session的原因和对策