当前位置:网站首页>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 边栏推荐
- After the win10 system uses the browser to download, the content is moved or deleted without reason
- RPC correction based on arcpy API
- 【WEBRTC】ADM: rtc_include_internal_audio_device 触发 RTC_DCHECK(adm) 断言
- How the FortiGate firewall rejects a port by using the local in policy policy
- DBT product initial experience
- FortiGate performs DNAT mapping, and intranet users cannot normally access the mapping
- Tea mall system based on SSM framework [project source code + database script + report]
- Internship: interface case implementation
- base64.c
- Myrpc version 5
猜你喜欢

Day 11 script and game AI

Configure specific source IP in SLA detection of FortiGate sdwan

深度融合云平台,对象存储界的“学霸”ObjectScale来了
![Blue Bridge Cup: magic cube rotation [Vocational group]](/img/ba/aeae2744f3aaa1052b5af452f990e2.jpg)
Blue Bridge Cup: magic cube rotation [Vocational group]

iMile 利用 Zadig 多云环境周部署千次,跨云跨地域持续交付全球业务

进程间通信之匿名管道

El upload upload file (manual upload, automatic upload, upload progress)

技术分享| 融合调度中的广播功能设计

Robot slam navigation core technology and practice Season 1: Chapter 0_ Slam development overview

I spent three years in a big factory outsourcing, which subverted my understanding!
随机推荐
【WEBRTC】ADM: rtc_ include_ internal_ audio_ Device triggers RTC_ Dcheck (ADM) assertion
Implementation steps of dynamic proxy
Es2019 key summary
AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里
Interview topic of MySQL
Error encountered in SQL statement, solve
FortiGate configures multiple server IPS as link monitor monitoring objects on the same interface
If you encounter problems when using spark for the first time, please ask for help
Unity 在編輯器中輸入字符串時,轉義字符的輸入
Junior students summarize JS advanced interview questions
SQLyog导入数据库时报错,求帮解决!
7-3 打怪升级 单源最短路
I spent three years in a big factory outsourcing, which subverted my understanding!
Detailed explanation of network layer
Ananagrams(UVA156)
errno和perror
Project safety and quality
Clients accessing the daytime service (TCP)
Pig-Latin (UVA492)
JS proxy