当前位置:网站首页>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 边栏推荐
- How to solve the problem of link hyperlinks when trying to link the database?
- Interface testing -- how to analyze an interface?
- thinkphp5实现导入功能
- 【WEBRTC】ADM: rtc_ include_ internal_ audio_ Device triggers RTC_ Dcheck (ADM) assertion
- Error encountered in SQL statement, solve
- Es2018 key summary
- FortiGate firewall modifies the default timeout of a session
- Memorize unfamiliar words at SSM stage and update them from time to time
- Ora-00907: missing right parenthesis problem supplement
- Explain the underlying principles of JVM garbage collection in simple terms
猜你喜欢

Basic knowledge of redis

How to use div boxes to simulate line triangles

Sql语句遇到的错误,求解

Interface testing -- how to analyze an interface?

lego_ Reading and summary of loam code

Anonymous pipeline for interprocess communication

Configure specific source IP in SLA detection of FortiGate sdwan

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

Myrpc version 4

第九天 脚本與資源管理
随机推荐
Sql语句遇到的错误,求解
Modifier of JS regular expression
Qt6 QML Book/Qt Quick 3D/Qt Quick 3D
Thinkphp5 implements import function
JS inheritance
FortiGate firewall configuration link detection link monitor and status query
Grasp grpc communication framework in simple terms
Unity échappe à l'entrée de caractères lors de l'entrée de chaînes dans l'éditeur
第九天 脚本與資源管理
Interview topic of MySQL
Detailed explanation of network layer
If you encounter problems when using spark for the first time, please ask for help
Daily summary of code knowledge
mysql更新数组形式的json串
internship:接口案例实现
Code cloud fatal: authentication failed for
Day 12 advanced programming techniques
Indefinite parameters of JS function
El upload Upload file (Manual upload, Automatic upload, upload progress)
【WEBRTC】ADM: rtc_ include_ internal_ audio_ Device triggers RTC_ Dcheck (ADM) assertion