ExecutorService异步线程池配置
时间: 2024-08-07 19:01:07 浏览: 72
ExecutorService是Java并发工具包中的一个核心组件,用于管理一组线程执行任务。它提供了一种将任务提交到线程池并控制其生命周期的方式。配置异步线程池通常涉及以下几个关键参数:
1. **固定大小** (`Executors.newFixedThreadPool()`):创建一个固定大小的线程池,一旦池中有可用线程处理任务,新的请求将进入队列等待执行。
2. **可缓存大小** (`Executors.newCachedThreadPool()`):动态调整线程数,当任务到来且所有线程忙时,新线程会自动添加,当空闲线程过多时,会回收一些。
3. **单线程模型** (`Executors.newSingleThreadExecutor()`):只有一个工作线程,适用于需要串行化执行的任务。
4. **定时及周期性任务** (`ScheduledExecutorService`):除了执行常规任务外,还可以安排在未来某个时间点或定期执行的任务。
配置时,你可以通过`newWorkStealingPool()`、`newScheduledThreadPool()`等方法设置其他高级特性,如优先级排序、拒绝策略等。重要的是要根据应用需求合理选择线程池大小和配置,避免资源浪费或阻塞。
相关问题
java的异步线程池策略模式的使用
### Java 中使用异步线程池与策略模式
在Java中,结合异步线程池和策略模式可以有效地提高程序的灵活性和可维护性。下面是一个具体的例子,展示了如何利用`ExecutorService`接口作为线程池,并通过策略模式来决定不同的任务处理方式。
#### 定义策略接口
首先定义一个通用的任务处理器接口 `TaskHandler` ,该接口有一个抽象方法用来执行特定类型的业务逻辑:
```java
public interface TaskHandler {
void execute();
}
```
#### 实现具体策略类
针对不同类型的任务创建多个实现了上述接口的具体类。这里假设存在两种类型的任务——CPU密集型任务(`CpuIntensiveTask`) 和 I/O 密集型任务 (`IoIntensiveTask`) :
对于 CPU 密集型任务:
```java
import java.util.Random;
public class CpuIntensiveTask implements TaskHandler {
@Override
public void execute() {
Random random = new Random();
int sum = 0;
for (int i = 0; i < Integer.MAX_VALUE / 1000; ++i) {
sum += Math.pow(random.nextInt(), 2);
}
System.out.println("Finished executing a CPU intensive task with result " + sum % 100); // 只打印最后两位数以节省空间
}
}
```
对于I/O密集型任务:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class IoIntensiveTask implements TaskHandler {
private final String filePath;
public IoIntensiveTask(String path){
this.filePath=path;
}
@Override
public void execute(){
try{
Files.readAllLines(Paths.get(filePath));
System.out.println("Read file at "+filePath+" successfully.");
}catch(IOException e){
throw new RuntimeException(e.getMessage());
}
}
}
```
#### 构建工厂模式生产相应实例
为了简化客户端代码并隐藏内部细节,可以通过静态工厂方法返回合适的对象给调用者:
```java
public enum TaskFactory {
INSTANCE;
public TaskHandler createNewInstance(TaskType type, Object... args){
switch(type){
case CPU_INTENSIVE -> {return new CpuIntensiveTask();}
case IO_INTENSIVE -> {if(args.length>0 && args[0] instanceof String str){return new IoIntensiveTask(str);}else{throw new IllegalArgumentException();}}
default->throw new UnsupportedOperationException("Unsupported operation");
}
}
}
enum TaskType{
CPU_INTENSIVE,
IO_INTENSIVE
}
```
#### 配置线程池
根据之前提到的不同工作负载特性配置适合各自特点的线程池[^3]:
- 对于CPU密集型任务采用固定大小的小规模线程池;
- 而对于I/O密集型则可以选择较大的线程池甚至无界缓存线程池。
```java
import java.util.concurrent.*;
class ThreadPoolConfigurator {
static ExecutorService getCpuBoundPool(int coreSize){
return Executors.newFixedThreadPool(coreSize,new NamedThreadFactory("cpu-bound"));
}
static ExecutorService getIoBoundPool(){
return new ThreadPoolExecutor(
Runtime.getRuntime().availableProcessors(),
Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<>(),
new NamedThreadFactory("io-bound")
);
}
}
```
注意这里的自定义线程命名是为了方便调试跟踪日志信息,在实际开发过程中推荐这样做。
#### 应用场景下的集成测试案例
现在有了这些组件之后就可以编写一段简单的测试代码来看看整个流程是如何运作起来的了:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
public class AsyncStrategyPatternDemo {
public static void main(String[] args)throws InterruptedException {
List<Runnable> tasks=new ArrayList<>();
Runnable cpuTask=()->TaskFactory.INSTANCE.createNewInstance(TaskType.CPU_INTENSIVE).execute();
Runnable ioTask=()->TaskFactory.INSTANCE.createNewInstance(TaskType.IO_INTENSIVE,"/path/to/file").execute();
// Add multiple instances of both types into the list.
IntStream.rangeClosed(1,5).forEach(i->{tasks.add(cpuTask);});
IntStream.rangeClosed(1,7).forEach(i->{tasks.add(ioTask);});
// Create thread pools based on different workloads.
ExecutorService cpuPool=ThreadPoolConfigurator.getCpuBoundPool(Runtime.getRuntime().availableProcessors()/2);
ExecutorService ioPool=ThreadPoolConfigurator.getIoBoundPool();
// Submit all tasks to corresponding executor services according their nature.
tasks.forEach(task->{
if(((TaskWrapper)((RunnableProxy)task)).getOriginalTarget()instanceof CpuIntensiveTask){
cpuPool.submit(task);
} else {
ioPool.submit(task);
}
});
// Shutdown executors after completion.
cpuPool.shutdown();
ioPool.shutdown();
cpuPool.awaitTermination(Long.MAX_VALUE,TimeUnit.NANOSECONDS);
ioPool.awaitTermination(Long.MAX_VALUE,TimeUnit.NANOSECONDS);
System.out.println("All asynchronous operations have been completed!");
}
}
```
在这个例子中,先准备了一系列混合着CPU密集型和I/O密集型的任务列表;接着分别初始化两个不同特性的线程池去提交对应种类的任务;最后等待所有的子线程结束再继续往下走。
java 通过配置类配置Executor线程池ExecutorService ThreadPoolTaskExecutor配置
在Java中,可以使用配置类来配置Executor线程池。其中,常用的实现类是`ExecutorService`和`ThreadPoolTaskExecutor`。
首先,需要创建一个配置类,可以命名为`ThreadPoolConfig`或者其他你喜欢的名称。在这个类中,你需要使用`@Configuration`注解来标识它是一个配置类,并且使用`@EnableAsync`注解来启用异步执行。
接下来,你需要定义一个`ExecutorService`或`ThreadPoolTaskExecutor` Bean,并使用`@Bean`注解将其标识为一个Bean。你可以根据项目的需求来选择使用哪个实现类。
如果选择使用`ExecutorService`,可以按照以下方式配置:
```java
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Bean
public ExecutorService executorService() {
return Executors.newFixedThreadPool(10); // 配置线程池的大小
}
}
```
如果选择使用`ThreadPoolTaskExecutor`,可以按照以下方式配置:
```java
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); // 设置核心线程数
executor.setMaxPoolSize(20); // 设置最大线程数
executor.setQueueCapacity(30); // 设置队列容量
executor.setThreadNamePrefix("my-executor-"); // 设置线程名称前缀
executor.initialize(); // 初始化
return executor;
}
}
```
在上述配置中,你可以根据实际需求来设置线程池的大小、队列容量等参数。通过这种方式,你就可以在应用程序中注入`ExecutorService`或`ThreadPoolTaskExecutor`,并使用它来执行异步任务。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)