天天看点

JAVA 适用于异步定时任务的自定义线程池[一]

1,定义ThreadPoolTaskExecutor

@Bean
    public ThreadPoolTaskExecutor terminalActivityDetectionTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setMaxPoolSize(terminalJobActivityDetectionProperties.getMaxPoolSize());
        threadPoolTaskExecutor.setCorePoolSize(terminalJobActivityDetectionProperties.getCorePoolSize());
        threadPoolTaskExecutor.setQueueCapacity(terminalJobActivityDetectionProperties.getQueueCapacity());
        threadPoolTaskExecutor.setThreadNamePrefix(terminalJobActivityDetectionProperties.getThreadNamePrefix());
        threadPoolTaskExecutor.setKeepAliveSeconds(terminalJobActivityDetectionProperties.getKeepAliveSeconds());
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.setTaskDecorator(MagicalRunnableWrapper::new);
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }           

此处,bean name 为 terminalActivityDetectionTaskExecutor

2,在具体的实现类中注入Bean

private final ThreadPoolTaskExecutor terminalActivityDetectionTaskExecutor;

    public TerminalActivityDetectionServiceImpl(ThreadPoolTaskExecutor terminalActivityDetectionTaskExecutor) {
        this.terminalActivityDetectionTaskExecutor = terminalActivityDetectionTaskExecutor;
    }           

3,调用execute方法。

terminalActivityDetectionTaskExecutor.execute(() -> {
    //此处编写具体的任务执行代码
});