当前位置:网站首页>Use of thread pool
Use of thread pool
2022-07-05 20:43:00 【Novice Xiaowang】
1. Thread pool usage scenario
java Multithreading is often used to handle some business , We strongly do not recommend using inheritance alone Thread Or realize Runnable Interface to create threads , In that case, it is bound to cost resources to create and destroy threads 、 Thread context switching problem . At the same time, creating too many threads may also lead to the risk of resource exhaustion , It is reasonable to introduce thread pool at this time , Facilitate the management of thread tasks .java The related classes related to thread pool in jdk1.5 At the beginning java.util.concurrent In bag , Several core classes and interfaces involved include :Executor、Executors、ExecutorService、ThreadPoolExecutor、FutureTask、Callable、Runnable etc. .
Thread pools can :
Speed up request response ( Response time first )
Speed up the handling of major tasks ( Throughput priority )
Using process
// Creating a thread pool
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 10, 30, TimeUnit.SECONDS, new SynchronousQueue<>());
// Submit tasks to the thread pool No return value
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
}
});
// Submit tasks to the thread pool There is a return value
Future<String> submit = threadPoolExecutor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("threadPoolExecutor submit");
return "null";
}
});
// Returns the execution result of the task
try {
Object o = submit.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// Close thread pool
threadPoolExecutor.shutdown();
Creation of thread pool
Thread pools can be created automatically or manually ,
Automatically create
Automatic creation is reflected in Executors In the tool class , Common can create newFixedThreadPool、newCachedThreadPool、newSingleThreadExecutor、newScheduledThreadPool;
// Automatically create different types of thread pools , Use Executors class , Fewer parameters are specified
// Manually create and use ThreadPoolExecutor , You can specify multiple parameters
// Create a thread pool , It can be scheduled to run commands after a given delay or to execute on a regular basis
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
System.out.println(" Delay the execution by four seconds ");
}
},4, TimeUnit.SECONDS);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(" Delay 1S after , every other 3 One second ");
}
},1,3,TimeUnit.SECONDS);
// Returns a thread pool ( This thread pool has only one thread ), This thread pool can be used after a thread dies ( Or when something goes wrong )
// Restart a thread to replace the original thread to continue execution
ExecutorService executorService = Executors.newSingleThreadExecutor();
// Create a thread pool that can reuse a fixed number of threads , Run these threads in a shared, unbounded queue
ExecutorService executorService1 = Executors.newFixedThreadPool(3);
// Create a thread pool that can create new threads as needed , But the previously constructed threads will be reused when they are available
ExecutorService executorService2 = Executors.newCachedThreadPool();Manually create
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 10, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());Manual creation is reflected in the flexible setting of various parameters of thread pool , Embodied in the code, that is ThreadPoolExecutor The difference of each argument on the class constructor :
// Create thread pool manually
/*
corePoolSize: Number of core threads , It is also the number of resident threads in the thread pool , When the thread pool is initialized, there are no threads by default , When the task comes, it starts to create a thread to execute the task
maximumPoolSize: Maximum number of threads , Some non core threads may be added to the number of core threads , It should be noted that only when workQueue More than... Will be created when the queue is full corePoolSize The thread of ( The total number of threads in the thread pool does not exceed maxPoolSize)
keepAliveTime: The idle time of non core thread exceeds keepAliveTime Will be automatically terminated and recycled , Pay attention to when corePoolSize=maxPoolSize when ,keepAliveTime Parameters don't work ( Because there are no non core threads );
unit:keepAliveTime Time unit of
workQueue: The queue used to hold the task , Can be unbounded 、 bounded 、 Simultaneous handover new SynchronousQueue<>() One of three queue types , When the number of worker threads in the pool is greater than corePoolSize when , At this time, the new task will be put in the queue
threadFactory: Create a factory class for threads , By default Executors.defaultThreadFactory(), You can also use guava Library ThreadFactoryBuilder To create
handler: The thread pool cannot continue to receive tasks ( The queue is full and the number of threads reached maximunPoolSize) Saturation strategy at , Values are AbortPolicy、CallerRunsPolicy、DiscardOldestPolicy、DiscardPolicy
*/
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 10, 30, TimeUnit.SECONDS, new SynchronousQueue<>());
workQueue queue
SynchronousQueue( Synchronous handover queue ): Queues are not used as a buffer for tasks , It can be simply understood that the queue length is zero
LinkedBlockingQueue( Unbounded queue ): The queue length is unlimited , When there are more and more requests ( The task processing speed cannot keep up with the task submission speed, resulting in request accumulation ) May cause excessive memory usage or OOM
ArrayBlockintQueue( Bounded queues ): Queue length is limited , When the queue is full, you need to create extra threads to perform tasks
handler Refusal strategy
- AbortPolicy: Interrupt throws an exception
- DiscardPolicy: Silently discard the task , Without any notice
- DiscardOldestPolicy: Discard the task that has been in the queue for the longest time
- CallerRunsPolicy: Let the thread submitting the task execute the task ( Compared with the first three, it is more friendly )
Close thread pool
shutdownNow(): Close thread pool now ( violence ), Ongoing and queued tasks will be interrupted , At the same time, this method will return the task list in the interrupted queue
shutdown(): Smoothly close the thread pool , The tasks in progress and in the queue can be completed , Subsequent incoming tasks will be rejected
isTerminated(): When the task being executed and all the tasks in the column are executed ( Empty ) It will return to true
Thread pool thread Reuse Principle
1. Tasks are executed in the thread pool , The core logic is ThreadPoolExecutor Class execute In the method , meanwhile ThreadPoolExecutor In the maintenance of HashSet<Worker> workers;
2.addWorker() Method to create a thread to execute a task , If it is the task of the core thread , Will be assigned to Worker Of firstTask attribute ;
3.Worker Realized Runnable, In essence, it is also a task , The core in the run() In the method ;
4.run() The execution core of the method runWorker(), Spin take task while (task != null || (task = getTask()) != null)),task Is the core thread Worker Of firstTask perhaps getTask();
5.getTask() Core logic of :
1. If the current number of worker threads is greater than the number of core threads -> It indicates that this thread is a non core worker thread , adopt poll() Take the task , If you don't get the task getTask() return null, Then in processWorkerExit(w, completedAbruptly) Method to release the reference of this non core worker thread ;
2. If the current number of worker threads is less than the number of core threads -> It shows that the thread is the core working thread at this time , adopt take() Take the task
3.take() Way to get the task , If there are no tasks in the queue, it will call await() Block the current thread , Until a new mission comes , So the core worker thread will not be recycled ; When executed execute In the method workQueue.offer(command) Called when Condition.singal() Method wakes up a previously blocked thread , In this way, the core thread can be reused

Callable and Runnable
Runnable and Callable Can be understood as a task , It encapsulates the specific logic of the task , Submit to the thread pool for execution , The difference lies in Runnable Task execution has no return value , And Runnable Task logic cannot pass throws Throw out cheched abnormal ( But it can. try catch), and Callable You can get the return value of the execution result of the task and throw checked abnormal .
Future and FutureTask
Future Interface is used to represent the result memory of executing asynchronous tasks , When the execution time of a task is too long, this method can be adopted : Submit the task to the sub thread for processing , The main thread doesn't have to wait synchronously , When a thread pool is submitted Callable or Runnable The task will return Future, use Future You can get the return result of task execution .
Future The main methods include :
get() Method : Returns the execution result of the task , If the task has not been completed , It will block until it is finished , If an exception occurs during execution , Throw an exception , But the main thread is imperceptible and unaffected , Unless calls get() Method will throw ExecutionException abnormal ;
get(long timeout, TimeUnit unit): Return the execution result of the task within the specified time , If the timeout does not return, it will throw TimeoutException, At this time, you need to explicitly cancel the task ;
cancel(boolean mayInterruptIfRunning): Cancel the task ,boolean Type input parameter indicates whether to force interruption if the task is running ;
isDone(): Determine if the task has been completed , The completion of execution does not mean that the task must be successfully executed , For example, the task execution fails but it is also completed 、 When the task is interrupted and finished, it will return true, It only represents a state that the following tasks will not be executed ;
isCancelled(): Judge whether the task is cancelled ;
边栏推荐
猜你喜欢

Abnova blood total nucleic acid purification kit pre installed relevant instructions

PHP反序列化+MD5碰撞
![[record of question brushing] 1 Sum of two numbers](/img/ea/4e981edd5570b49b4fa909ac8da6c4.png)
[record of question brushing] 1 Sum of two numbers

如何形成规范的接口文档

Duchefa low melting point agarose PPC Chinese and English instructions

解析创客教育的知识迁移和分享精神

Introduction to dead letter queue (two consumers, one producer)

Return to blowing marshland -- travel notes of zhailidong, founder of duanzhitang

Practical demonstration: how can the production research team efficiently build the requirements workflow?

死信队列入门(两个消费者,一个生产者)
随机推荐
小程序代码的构成
E. Singhal and numbers (prime factor decomposition)
14、Transformer--VIT TNT BETR
Usaco3.4 "broken Gong rock" band raucous rockers - DP
y57.第三章 Kubernetes从入门到精通 -- 业务镜像版本升级及回滚(三十)
CVPR 2022 | common 3D damage and data enhancement
Return to blowing marshland -- travel notes of zhailidong, founder of duanzhitang
Abbkine BCA法 蛋白质定量试剂盒说明书
Duchefa细胞分裂素丨二氢玉米素 (DHZ)说明书
Abnova blood total nucleic acid purification kit pre installed relevant instructions
Frequent MySQL operations cause table locking problems
Informatics Olympiad 1337: [example 3-2] word search tree | Luogu p5755 [noi2000] word search tree
Abnova丨CRISPR SpCas9 多克隆抗体方案
信息学奥赛一本通 1339:【例3-4】求后序遍历 | 洛谷 P1827 [USACO3.4] 美国血统 American Heritage
mongodb基操的练习
AI automatically generates annotation documents from code
Is it safe to open a stock account by mobile phone? My home is relatively remote. Is there a better way to open an account?
中国管理科学研究院凝聚行业专家,傅强荣获智库专家“十佳青年”称号
[UE4] unrealinsight obtains the real machine performance test report
Prosci LAG-3 recombinant protein specification