天天看點

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(() -> {
    //此處編寫具體的任務執行代碼
});