当前位置:网站首页>Use of thread pool
Use of thread pool
2022-06-30 04:22:00 【No bug program yuan】
Code example :
newFixedThreadPool: A pool of five threads
public static void main(String[] args){
// Five threads in one pool
ExecutorService threadPool=Executors.newFixedThreadPool(5);
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t Handle the business ");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
// Execution results thread To the most 5
pool-1-thread-1 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-5 Handle the business
pool-1-thread-4 Handle the business
pool-1-thread-3 Handle the business newSingleThreadExecutor: How many requests are handled by only one thread :
public static void main(String[] args){
// One pool, one thread
ExecutorService threadPool=Executors.newSingleThreadExecutor();
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t Handle the business ");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
// Execution results :
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
newCachedThreadPool: Multiple threads in one pool :
public static void main(String[] args){
// A pool N Processing threads , If one thread can handle one thread, if it is busy, there will be multiple threads
ExecutorService threadPool=Executors.newCachedThreadPool();
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t Handle the business ");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
// Execution results :
pool-1-thread-1 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-3 Handle the business
pool-1-thread-4 Handle the business
pool-1-thread-5 Handle the business
pool-1-thread-6 Handle the business
pool-1-thread-7 Handle the business
pool-1-thread-8 Handle the business
pool-1-thread-9 Handle the business
pool-1-thread-10 Handle the business public static void main(String[] args){
// A pool N Processing threads , If one thread can handle one thread, if it is busy, there will be multiple threads
ExecutorService threadPool=Executors.newCachedThreadPool();
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t Handle the business ");
});
// Get some sleep , When you are too busy, a thread will handle it
Thread.sleep(300);
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
// Execution results :
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
The underlying principle of thread pool :
//newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
//newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
//newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}The three threading methods are all adjustable ThreadPoolExecutor Interpretation of parameters :
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
}1.corePoolSize:
1.1 After the thread pool is created , When a request comes , The thread in the pool will be arranged to perform the request task , Approximately understood as Today's on duty thread
1.2 When the number of threads in the thread pool reaches corePoolSize after , The arriving task is placed in the cache queue ;
2.maximumPoolSize
The thread pool can hold the maximum number of threads executing at the same time , This value must be greater than or equal to 1 .
3.keepAliveTime:
Extra free thread lifetime .
The current number of thread pools exceeds corePoolSize when , When the free time reaches keepAliveTime When the value of , Redundant idle threads are destroyed until only corePoolSize Up to threads .
4.TimeUnit unit
keepAliveTime The unit of
5.workQueue( Blocking queues )
Task queue , Tasks submitted but not yet performed ( The waiting area inside the bank )
6.threadFactory
Represents the thread factory that generates the worker threads in the thread pool , For thread creation, the default is used ( Create thread features ).
7. handler
Refusal strategy , Indicates that when the queue is full and the worker thread is greater than or equal to the maximum thread of the thread pool maximumPoolSize
summary : First the request came ,corePoolSize Number of threads started processing , The following requests are saved to Blocking queues workQueue, When corePoolSize and workQueue Expand the capacity when it is full ( Ask for support , Add thread processing ), It's expanded to maximumPoolSize value ( Maximum thread ) If there are still requests, you can directly enable the reject policy , If the business volume slows down , stay keepAliveTime There is no request after the time of variable setting , Just remove the supported threads corePoolSize All external threads are destroyed .
What is a rejection strategy :
The waiting line is full , There are no more new tasks to fill. At the same time, there are max Threads have also reached , Can't continue serving new tasks . At this time, we need to reasonably deal with the problem of rejection strategy mechanism .
1.AbortPolicy( Default ): Direct selling RejectedExecutionException Exceptions prevent the system from functioning properly .
2.callerRunsPolicy:“ The caller runs a regulatory mechanism , The strategy will not abandon the task , It doesn't throw an exception , Instead, some tasks are rolled back to the caller ,
3.DiscardoidestPolicy: Discard the task waiting the longest in the queue , Then add the current task to the queue and try to submit the current task again .
4.DiscardPolicy: Discard tasks directly , No processing and no exception thrown . If the task is allowed to be lost , This is the best plan .
AbortPolicy Refusal strategy Example :
public static void main(String[] args) {
ExecutorService threadPool =new ThreadPoolExecutor(2,5,
11, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
try{
for (int i = 1; i <=9 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t Handle the business ");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
// Execution results :
pool-1-thread-1 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-3 Handle the business
pool-1-thread-4 Handle the business
pool-1-thread-5 Handle the business
java.util.concurrent.RejectedExecutionException: Task com.hy.controller.ResController$$Lambda$1/[email protected] rejected from [email protected][Running, pool size = 5, active threads = 4, queued tasks = 0, completed tasks = 4]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at com.hy.controller.ResController.main(ResController.java:1017)
CallerRunsPolicy Example : Back to the caller
public static void main(String[] args) {
ExecutorService threadPool =new ThreadPoolExecutor(2,5,
11, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t Handle the business ");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
// Execution results :
main Handle the business
main Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-3 Handle the business
pool-1-thread-4 Handle the business
pool-1-thread-5 Handle the business DiscardOldestPolicy Example :
public static void main(String[] args) {
ExecutorService threadPool =new ThreadPoolExecutor(2,5,
11, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t Handle the business ");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
// Execution results
pool-1-thread-2 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-3 Handle the business
pool-1-thread-5 Handle the business
pool-1-thread-4 Handle the business DiscardPolicy Example :
public static void main(String[] args) {
ExecutorService threadPool =new ThreadPoolExecutor(2,5,
11, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardPolicy());
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t Handle the business ");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
// Execution results :
pool-1-thread-1 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-1 Handle the business
pool-1-thread-2 Handle the business
pool-1-thread-4 Handle the business
pool-1-thread-3 Handle the business
pool-1-thread-5 Handle the business 边栏推荐
- Implementation steps of dynamic proxy
- Error in conditional filter (if) syntax in sum function in SQL Server2005
- [cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)
- Es2018 key summary
- 2021-11-04
- 找到接口在表单里加参数
- JS file block to Base64 text
- OneNote production schedule
- Default value of JS parameter
- About manipulator on Intelligent Vision Group
猜你喜欢

How to use div boxes to simulate line triangles

An error occurs when sqlyog imports the database. Please help solve it!

El upload Upload file (Manual upload, Automatic upload, upload progress)

Myrpc version 4
![Blue Bridge Cup: magic cube rotation [Vocational group]](/img/ba/aeae2744f3aaa1052b5af452f990e2.jpg)
Blue Bridge Cup: magic cube rotation [Vocational group]

Myrpc version 1

FortiGate firewall quick initialization administrator password

FortiGate configures multiple server IPS as link monitor monitoring objects on the same interface

lego_ Reading and summary of loam code

Redis sentry, persistence, master-slave, hand tear LRU
随机推荐
Collinearity problem
Concatenation of Languages(UVA10887)
Knowledge - how to build rapport in sales with 3 simple skills
Stack implementation integrated Calculator - code implementation
Qt6 QML Book/Qt Quick 3D/Qt Quick 3D
Junior students summarize JS basic interview questions
SQL error caused by entity class: Oracle "ora-00904" error: possible case of invalid identifier
Myrpc version 6
FortiGate performs DNAT mapping, and intranet users cannot normally access the mapping
JS deconstruction assignment
The new paradigm of AI landing is "hidden" in the next major upgrade of software infrastructure
第十天 数据的保存与加载
Indefinite parameters of JS function
How the FortiGate firewall rejects a port by using the local in policy policy
7-3 打怪升级 单源最短路
[learn FPGA programming from scratch -52]: high level chapter - FPGA development based on IP core - basic framework for IP core use (taking PLL as an example)
Splicing strings with custom functions
Node red series (28): communication with Siemens PLC based on OPC UA node
Modifier of JS regular expression
thinkphp5实现导入功能