当前位置:网站首页>Introduction to ThreadPoolExecutor
Introduction to ThreadPoolExecutor
2022-06-21 10:42:00 【Borny Ding Ding】
1、 brief introduction
Executor The framework includes the management of thread pool , Provides a thread factory 、 Queue and reject policy, etc ,Executor Frameworks make concurrent programming easier . Thread pool implementation class ThreadPoolExecutor yes Executor The core class of the framework .
2、 Simple example
(1)MyRunnable.java
package cn.hwd.tpe.service;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MyRunnable implements Runnable {
@Override
public void run() {
log.info(Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
log.error(e.getMessage());
}
}
}
(2)Application.java
package cn.hwd.tpe;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import cn.hwd.tpe.service.MyRunnable;
@SpringBootApplication
public class Application implements CommandLineRunner {
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final int QUEUE_CAPACITY = 100;
private static final Long KEEP_ALIVE_TIME = 1L;
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
// Use ThreadPoolExecutor Constructor to create thread pool by defining parameters
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE, // Number of core threads in thread pool
MAX_POOL_SIZE, // The maximum number of threads in the thread pool
KEEP_ALIVE_TIME, // When the number of threads is greater than the number of core threads , The maximum time an extra idle thread can survive
TimeUnit.SECONDS, // Time unit
new ArrayBlockingQueue<>(QUEUE_CAPACITY), // Task queue , Used to store a queue of waiting tasks
new ThreadPoolExecutor.CallerRunsPolicy());// Refusal strategy , When too many tasks are submitted that cannot be processed in time , We can customize strategies to handle tasks
for (int i = 0; i < 10; i++) {
// establish WorkerThread object (WorkerThread Class implements the Runnable Interface )
Runnable worker = new MyRunnable();
// perform Runnable
executor.execute(worker);
}
// Terminate thread pool
executor.shutdown();
while (!executor.isTerminated()) {
}
}
}
3、 Running results
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.20.RELEASE)
2019-12-17 11:14:10.092 INFO 9172 --- [ main] cn.hwd.tpe.Application : Starting Application on LAPTOP-N1UHE4RC with PID 9172 (D:\workspace\work\test\thread-pool-executor\bin started by vineg in D:\workspace\work\test\thread-pool-executor)
2019-12-17 11:14:10.096 INFO 9172 --- [ main] cn.hwd.tpe.Application : No active profile set, falling back to default profiles: default
2019-12-17 11:14:10.146 INFO 9172 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]757acd7b: startup date [Tue Dec 17 11:14:10 CST 2019]; root of context hierarchy
2019-12-17 11:14:10.726 INFO 9172 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2019-12-17 11:14:10.741 INFO 9172 --- [pool-1-thread-1] cn.hwd.tpe.service.MyRunnable : pool-1-thread-1
2019-12-17 11:14:10.742 INFO 9172 --- [pool-1-thread-2] cn.hwd.tpe.service.MyRunnable : pool-1-thread-2
2019-12-17 11:14:10.744 INFO 9172 --- [pool-1-thread-3] cn.hwd.tpe.service.MyRunnable : pool-1-thread-3
2019-12-17 11:14:10.749 INFO 9172 --- [pool-1-thread-4] cn.hwd.tpe.service.MyRunnable : pool-1-thread-4
2019-12-17 11:14:10.751 INFO 9172 --- [pool-1-thread-5] cn.hwd.tpe.service.MyRunnable : pool-1-thread-5
2019-12-17 11:14:15.742 INFO 9172 --- [pool-1-thread-1] cn.hwd.tpe.service.MyRunnable : pool-1-thread-1
2019-12-17 11:14:15.743 INFO 9172 --- [pool-1-thread-2] cn.hwd.tpe.service.MyRunnable : pool-1-thread-2
2019-12-17 11:14:15.746 INFO 9172 --- [pool-1-thread-3] cn.hwd.tpe.service.MyRunnable : pool-1-thread-3
2019-12-17 11:14:15.751 INFO 9172 --- [pool-1-thread-4] cn.hwd.tpe.service.MyRunnable : pool-1-thread-4
2019-12-17 11:14:15.752 INFO 9172 --- [pool-1-thread-5] cn.hwd.tpe.service.MyRunnable : pool-1-thread-5
2019-12-17 11:14:20.755 INFO 9172 --- [ main] cn.hwd.tpe.Application : Started Application in 10.966 seconds (JVM running for 11.431)
2019-12-17 11:14:20.756 INFO 9172 --- [ Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.spring[email protected]757acd7b: startup date [Tue Dec 17 11:14:10 CST 2019]; root of context hierarchy
2019-12-17 11:14:20.758 INFO 9172 --- [ Thread-2] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
边栏推荐
- Stream programming: stream support, creation, intermediate operation and terminal operation
- Inner class
- Starting a prairie fire, Alibaba cloud database "hundred cities gather together" to help small and medium-sized enterprises' digital intelligence transformation
- Classification of ram and ROM storage media
- support vector machine
- Research and implementation of embedded software framework based on multi process architecture
- Eureka's timedsupersortask class (periodic task with automatic interval adjustment)
- The first phase of takin open source training camp is coming! Teach you to complete the full link voltage test hand in hand!
- 知识点滴 - 什么是加速移动网页(AMP)?
- Odd number of characters exception
猜你喜欢

China international e-commerce center and Analysys jointly released: the national online retail development index in the fourth quarter of 2021 increased by 0.6% year on year

WCF RestFul+JWT身份验证

使用shapeit进行单倍型分析

Celsius 的暴雷,会是加密领域的“雷曼时刻”吗?

Performance optimization - image compression, loading and format selection

还在直接用localStorage么?全网最细:本地存储二次封装(含加密、解密、过期处理)
![leetcode:715. Range module [brainless segmenttree]](/img/70/6cfb071bb08b30945c31c4947d2cef.png)
leetcode:715. Range module [brainless segmenttree]

燎原之势 阿里云数据库“百城聚力”助中小企业数智化转型

ES复合查询工作量评估

西电AI专业排名超清北,南大蝉联全国第一 | 2022软科中国大学专业排名
随机推荐
[cloud based co creation] enterprise digitalization accelerates "new intelligent manufacturing"
如何将MindSpore模型转ONNX格式并使用OnnxRuntime推理---开发测试篇
One line of code accelerates sklearn operations thousands of times
Optional classes, convenience functions, creating options, optional object operations, and optional streams
程序員新人周一優化一行代碼,周三被勸退?
DSP gossip: how to save the compiled variables on the chip when the variables are defined in the code
Do website from scratch 11- blog development
Underlying principle of Concurrency: thread, resource sharing, volatile keyword
Get the data in the configuration file properties
Odd number of characters异常
Starting a prairie fire, Alibaba cloud database "hundred cities gather together" to help small and medium-sized enterprises' digital intelligence transformation
POI implements operation to generate word tables and operate chart data in word
Stream programming: stream support, creation, intermediate operation and terminal operation
Network multimedia -- linphone correlation analysis -- directory
Introduction to ground plane in unity
Dapr advanced-01-debug dapr
optional类,便利函数,创建Optional,Optional对象操作以及Optional流
Advanced part of concurrent programming: parallel flow, tasks and executors, and completabilefuture classes
NLog自定义Target之MQTT
The execution process before executing the main function after the DSP chip is powered on