1 ThreadPoolTaskExecutor thread pool:
ThreadPoolTaskExecutor is Spring’s secondary encapsulation based on Java’s own thread pool ThreadPoolExecutor. The main purpose is to make it more convenient in the spring framework system The thread pool is used in Spring, which is the default thread pool in Spring
2 Use ThreadPoolTaskExecutor to inject beans into ioc
Configuration file form, Spring will automatically configure
## 默认线程池配置,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
Configuration form:
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 After creating threads, all thread pools are obtained from ioc
4 Thread pool processing process:
(1) Check whether the core thread pool is full. If not, create a thread for execution Task, if the number of core threads is full, check whether the task queue is full. If not, store the thread in the task queue. If the task queue is full, check the maximum number of threads. If not, create a thread to execute the task. If it is full, execute according to the rejection policy
(2) Deny policy:
(2) Configuration class form:
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 Use ThreadPoolTaskScheduler scheduled taskUse for ordinary thread pool:
schedule(Runnable task,Trigger) schedule(Runnable task,Date)(2) Specify the interval to execute a task. The time interval is from the completion of the previous task to the start of the next task, in milliseconds
scheduleWithFixedDelay(Runnable task,long delay)(3) Execute tasks at a fixed frequency and execute new tasks at intervals after the task starts. If the last task is completed, wait for the last task to be completed before executing the next task
scheduleAtFixedRate(Runnable task,long delay)(4) Scheduled task cancellation:Set the collection where the scheduled task is stored. The result of the scheduled task execution is ScheduledFuture6b3d0130bba23ae47fe2b8e8cddf0195. Store the object in the collection and obtain the ScheduledFuturea3b2ddd0291c250434d69c141d68a812Object.cancel(true) cancels the scheduled task
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; }); } }Three @Scheduled implements the scheduled task, annotation enables the scheduled task1 Use @EnableScheduled to enable support2 @ Scheduled annotation method (1)@Scheduled(fixedDelay=5000) delayed execution, executed after 5s
(2)@Scheduled(fixedRate=5000) scheduled execution, executed every five seconds
(3)@Scheduled(corn="002**?") Custom execution, corn expression Baidu, this execution method is commonly used, corn="002**?" starts executing scheduled tasks at two o'clock in the morning every day
( 2) @Scheduled and @Async annotations enable scheduled tasks and specify the thread pool in @Async("pool"). If the thread pool is not specified, Spring's SimpleAsyncTaskExecutor thread pool will be used. This thread pool will add a thread to execute the task each time. , low efficiency
2 @Async turns on asynchronous tasks and specifies the thread pool
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()); } }Five: Present a custom java thread pool:
@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()); }
The above is the detailed content of How to implement Springboot's own thread pool. For more information, please follow other related articles on the PHP Chinese website!