@Configuration,@Autowired ExecutorService 不必重复初始化线程池

不必每次都重新写一遍线程池初始化的代码,只需要@Autowired  ExecutorService 即可。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @Desc 先把Bean注入,不然 @Autowired   private ExecutorService executorService; 会报错,
 **/
@Configuration //@Configuration 与 @Component 均可
//@Component
public class ThreadPoolConfig {
    @Bean
    public ExecutorService getThreadPool() {
        System.out.println("ExecutorService getThreadPool()...");
        return new ThreadPoolExecutor(2, 5, 10, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>());
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ExecutorService;

/**
 * @Desc
 **/
@Component
public class TestTask1 {

    @Autowired
    private ExecutorService executorService;

    public void f1() {
        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "," + new Date() + "executorService.submit...");
        });
    }

}
    <task:scheduled-tasks scheduler="weScheduler">
        <task:scheduled ref="testTask1" method="f1" cron="0/10 * * * * ?"/>
    </task:scheduled-tasks>

以上基于SpringBoot 2.0.2.RELEASE 和SpringTask定时任务,jdk1.8

输出:

pool-2-thread-1,Mon Nov 12 20:13:30 CST 2018executorService.submit...
pool-2-thread-2,Mon Nov 12 20:13:40 CST 2018executorService.submit...
pool-2-thread-1,Mon Nov 12 20:13:50 CST 2018executorService.submit...
pool-2-thread-2,Mon Nov 12 20:14:00 CST 2018executorService.submit...

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页