springboot自带线程池怎么实现
本文讲解"springboot自带线程池如何实现",希望能够解决相关问题。
一: threadpooltaskexecuto
1 threadpooltaskexecutor线程池:
threadpooltaskexecutor是spring基于java本身的线程池threadpoolexecutor做的二次封装,主要目的还是为了更加方便的在spring框架体系中使用线程池, 是spring中默认的线程池
2 使用threadpooltaskexecutor注入bean到ioc中
配置文件形式,spring会自动配置
## 默认线程池配置,threadpooltaskexecutor # 核心线程数 spring.task.execution.pool.core-size=8 # 最大线程数 spring.task.execution.pool.max-size=16 # 空闲线程存活时间 spring.task.execution.pool.keep-alive=60s # 是否允许核心线程超时 spring.task.execution.pool.allow-core-thread-timeout=true # 线程队列数量 spring.task.execution.pool.queue-capacity=100 # 线程关闭等待 spring.task.execution.shutdown.await-termination=false spring.task.execution.shutdown.await-termination-period= # 线程名称前缀 spring.task.execution.thread-name-prefix=demo_thread
配置形式:
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.concurrent.threadpooltaskexecutor;
import org.springframework.scheduling.concurrent.threadpooltaskscheduler;
import java.util.concurrent.concurrenthashmap;
import java.util.concurrent.concurrentmap;
import java.util.concurrent.executor;
import java.util.concurrent.scheduledfuture;
//@configuration
public class threadconfig {
@value("${task.maxpoolsize}")
private int maxpoolsize;
//todo 其他的相关配置都可以通过配置文件中注入
@bean("threadpooltaskexecutor")
public executor myasync() {
final threadpooltaskexecutor executor =
new threadpooltaskexecutor();
executor.setmaxpoolsize(maxpoolsize);
//todo 其他参数设置
//初始化
executor.initialize();
return executor;
}
}3 创建线程后全部从ioc中获取线程池子
4 线程池处理流程:
(1) 查看核心线程池是否已满,不满就创建一条线程执行任务,核心线程数量已满就查看任务队列是否已满不满就将线程存储在任务队列中任务队列已满,就查看最大线程数量,不满就创建线程执行任务,已满就按照拒绝策略执行
(2) 拒绝策略:
- callerrunspolicy():原来的线程执行
- abortpolicy():直接抛出异常
- discardpolicy():直接丢弃
- discardoldestpolicy():丢弃队列中最老的任
二: threadpooltaskscheduler
1 threadpooltaskscheduler 定时调度任务线程池,处理异步任务
2 使用方式: 注入 threadpooltaskscheduler的bean
(1) 配置文件形式:..
(2) 配置类形式:
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.concurrent.threadpooltaskscheduler;
import java.util.concurrent.concurrenthashmap;
import java.util.concurrent.concurrentmap;
import java.util.concurrent.scheduledfuture;
@configuration
public class threadpooltaskschedulerconfig {
@bean
public threadpooltaskscheduler threadpooltaskscheduler() {
final threadpooltaskscheduler threadpooltaskscheduler = new threadpooltaskscheduler();
//设置等待任务在关机时l候完成
threadpooltaskscheduler.setwaitfortaskstocompleteonshutdown(true);
//设置等待时间为60s
threadpooltaskscheduler.setawaitterminationseconds(60);
return threadpooltaskscheduler;
}
}3 使用threadpooltaskscheduler定时任务
做普通线程池使用:
- submit(callable),需要执行结果
- submit(runnable),不需要执行结果
(1) 定时任务
添加任务内容runnable,设置执行周期trigger/date,trigger表达式百度即可
schedule(runnable task,trigger) schedule(runnable task,date)
(2) 指定间隔时间执行一次任务,时间间隔是前一次任务完成到下一次任务开始,单位毫秒
schedulewithfixeddelay(runnable task,long delay)
(3) 固定频率执行任务,在任务开始后间隔一段时间执行新的任务,如果上次任务么执行完成,则等待上次任务执行完成后执行下次任务
scheduleatfixedrate(runnable task,long delay)
(4) 定时任务取消:
设置定时任务存储的集合,定时任务执行的结果为scheduledfuture<?>,将该对象存储到集合,通过在集合中获取scheduledfuture<?>对象.cancel(true)取消定时任务
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.scheduling.concurrent.threadpooltaskscheduler;
import org.springframework.scheduling.support.crontrigger;
import org.springframework.stereotype.service;
import java.text.dateformat;
import java.text.parseexception;
import java.text.simpledateformat;
import java.util.date;
import java.util.concurrent.*;
@service
public class schedulerservice {
@autowired
threadpooltaskscheduler scheduler;
/**
* 常规线程池使用
*/
public void tesscheduler1() throws executionexception, interruptedexception {
//无返回值
final future<?> demo_scheduler1 = scheduler.submit(new runnable() {
@override
public void run() {
system.out.println("demo runnable scheduler");
}
});
//无返回值
final future<?> demo_scheduler2 = scheduler.submit(new callable<object>() {
@override
public object call() throws exception {
system.out.println("demo callable scheduler");
return "callable";
}
});
system.out.println("result:" + demo_scheduler2.get());
}
/**
* 定时任务
*/
public void tesscheduler2() throws parseexception {
//crontrigger表达式百度即可
scheduler.schedule(() -> {
system.out.println("定时任务");
}, new crontrigger("0/1****?"));
//创建指定时间的日期
final date date = new date(2023, 3, 26, 21, 35);
final dateformat format = new simpledateformat();
final date parse = format.parse("2023-03-26-21-26");
scheduler.schedule(() -> {
system.out.println(new date());
}, parse);
}
/**
* 指定时间间隔执行任务,上次任务结束到下次任务开始的时间间隔
*/
public void tesscheduler3() {
scheduler.schedulewithfixeddelay(() -> {
//todo
}, 300l);
}
/**
* 固定频率执行任务,在固定一段时间后便会执行下次任务,
* 如果时间到了上次任务还没执行完毕则等待,
* 直到上一次任务执行完毕后立马执行下次任务
*/
public void tesscheduler4() {
scheduler.scheduleatfixedrate(new futuretask<string>(new callable<string>() {
@override
public string call() throws exception {
return null;
}
}),
200);
}
//取消定时任务队列
public static concurrentmap<string, scheduledfuture> map = new concurrenthashmap<>();
public void starttask(string k1) {
map.compute(k1, (k, v) -> {
if (map.containskey(k)) return v;
map.put(k, v);
return v;
});
}
}三 @scheduled实现定时任务,注解开启定时任务
1 使用@enablescheduled开启支持
2 @scheduled标注方法
(1)@scheduled(fixeddelay=5000)延迟执行,5s后执行
(2)@scheduled(fixedrate=5000)定时执行,每隔五秒就进行执行
(3)@scheduled(corn="002**?") 自定义执行,corn表达式百度,常用这种执行方式,corn="002**?"每天凌晨两点开始执行定时任务
3 注意@scheduled开启的任务是单线程的,容易阻塞
(1) 在ioc中注入threadpooltaskscheduler,则scheduled就使用threadpooltaskscheduler线程池,可以解决单线程阻塞问题
(2) @scheduled和@async注解开启定时任务,在@async("pool")中指定线程池,若是没有指定线程池会使用spring的simpleasynctaskexecutor线程池,这个线程池每次都会增加一个线程去执行任务,效率低下
四:spring中的异步任务
1 @enableasync开启异步支持
2 @async开启异步任务,指定线程池
注意:@scheduled和@async注解开启定时任务,在@async("pool")中指定线程池,若是没有指定线程池会使用spring的simpleasynctaskexecutor线程池,这个线程池每次都会增加一个线程去执行任务,效率低下但是@async单独开启异步任务,则使用的是默认的线程池,建议根据需求自定义线程池
注意:@async的返回值只能为void或future, 调用方和@async不能在一个类中,否则不走aop;
import org.springframework.scheduling.annotation.async;
import org.springframework.stereotype.service;
@service
public class asyncservice {
@async
public void showthreadname1() {
//默认线程池
system.out.println(thread.currentthread().getname());
}
@async("mypool")//指定线程池
public void showthreadname2() {
system.out.println(thread.currentthread().getname());
}
}五:献上一颗自java自定义线程池:
@bean("mypool")
public executor executor(){
return new threadpoolexecutor(// 自定义一个线程池
1, // coresize
2, // maxsize
60, // 60s
timeunit.seconds, new arrayblockingqueue<>(3) // 有界队列,容量是3个
, executors.defaultthreadfactory()
, new threadpoolexecutor.abortpolicy());
}java自带的线程池,缓存,固定数量的,单线程的,定时的,,,,六七种,后面续上
关于 "springboot自带线程池如何实现" 就介绍到此。希望多多支持硕编程。


