异步线程设置优先级
前提: @Async 注解可以实现异步功能,但是如果想让其中一些异步任务先于一些异步任务执行,那么这个注解就实现不了了。
参考大神文章:这篇文章,需要大显神通
解决思路:为ThreadPoolTaskExecutor使用PriorityBlockingQueue
配置
@Bean("CustomTaskExecutor")
public TaskExecutor threadPoolTaskExecutor(
@Value("${spring.async.core-pool-size}") int corePoolSize,
@Value("${spring.async.max-pool-size}") int maxPoolSize,
@Value("${spring.async.queue-capacity}") int queueCapacity) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor() {
@Override
protected BlockingQueue<Runnable> createQueue(int queueCapacity) {
return new PriorityBlockingQueue<>(queueCapacity);
}
};
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
//....你需要的其他配置
return executor;
}
这里的配置基本和使用@Async注解时配置线程池的无异,就是使用了PriorityBlockingQueue去为在等待队列中的线程设置优先级。
优先级比较
public class FutureCustomTask
extends FutureTask<FutureCustomTask> implements Comparable<FutureCustomTask> {
private JobTask task;
public FutureCustomTask(JobTask task) {
//这里null是因为执行任务不需要任何结果
super(task, null);
this.task = task;
}
@Override
public int compareTo(FutureCustomTask o) {
return task.getJob().getPriority().compareTo(o.task.getJob().getPriority());
}
}
调试和输出结果
String类型任务优先级高,List类型任务优先级低
//先来两个String任务,占满核心线程池 核心线程池大小为2!!!
taskExecutor.execute(new FutureCustomTask(
new JobTask(jobBusiness::doString,
new JobEntity(stringParam, 1L))));
taskExecutor.execute(new FutureCustomTask(
new JobTask(jobBusiness::doString,
new JobEntity(stringParam, 1L))));
//再来任务试试看是否为优先级高的先执行
//这里先放 List 优先级低的任务,如果优先级配置生效,它应该最后执行。
taskExecutor.execute(new FutureCustomTask(
new JobTask(jobBusiness::doList,
new JobEntity(lpParam, 2L))));
taskExecutor.execute(new FutureCustomTask(
new JobTask(jobBusiness::doString,
new JobEntity(stringParam, 1L))));
taskExecutor.execute(new FutureCustomTask(
new JobTask(jobBusiness::doString,
new JobEntity(stringParam, 1L))));
taskExecutor.execute(new FutureCustomTask(
new JobTask

该博客介绍了如何在Spring Boot中使用@Async注解实现异步任务,并通过ThreadPoolTaskExecutor配置PriorityBlockingQueue来设置任务优先级。通过创建自定义的FutureCustomTask类并实现Comparable接口,根据JobTask的优先级进行比较,确保高优先级任务优先执行。在测试中,验证了字符串任务优先级高于列表任务,实现了预期的执行顺序。
最低0.47元/天 解锁文章
1205

被折叠的 条评论
为什么被折叠?



