在配置类中创建了一个返回类型为 Executor 的 Bean,其名称定义为“threadPoolTaskExecutor”,并且重新设置了 ThreadPoolTaskExecutor 的核心线程池大小,默认为 1,现在修改为 5。
新进 AsyncService 类,内容如下:
public class AsyncService {@Async("threadPoolTaskExecutor")
public void execute() {
System.out.println(Thread.currentThread().getName());
}
}
@Async 注解上需要指定我们之前配置的线程池执行器“threadPoolTaskExecutor”。
新建 AsyncMain 类,内容如下:
public class AsyncMain {public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncConfig.class);
AsyncService service = context.getBean(AsyncService.class);
for (int i = 0; i < 10; i++) {
service.execute();
}
}
}
程序运行结果如下:
threadPoolTaskExecutor-1threadPoolTaskExecutor-2
threadPoolTaskExecutor-4
threadPoolTaskExecutor-3
threadPoolTaskExecutor-5
threadPoolTaskExecutor-3
threadPoolTaskExecutor-2
threadPoolTaskExecutor-4
threadPoolTaskExecutor-1
threadPoolTaskExecutor-5
从结果中可以看得出,线程池执行器变成了“threadPoolTaskExecutor”,并且大小为 5。
2)应用级别
新建 AsyncConfig 类,内容如下:
@Configuration@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Bean
public AsyncService getAsyncService() {
return new AsyncService();
}
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.initialize();
return executor;
}
}
需要实现 AsyncConfigurer 接口,并重写 getAsyncExecutor() 方法,这次设置线程池的大小为 3。注意执行器要执行一次 initialize() 方法。
新进 AsyncService 类,内容如下:
public class AsyncService {@Async
public void execute() {
System.out.println(Thread.currentThread().getName());
}
}
新建 AsyncMain 类,内容如下:
public class AsyncMain {public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncConfig.class);
AsyncService service = context.getBean(AsyncService.class);
for (int i = 0; i < 10; i++) {
service.execute();
}
}
}
程序运行结果如下:
ThreadPoolTaskExecutor-2ThreadPoolTaskExecutor-2
ThreadPoolTaskExecutor-2
ThreadPoolTaskExecutor-2
ThreadPoolTaskExecutor-2
ThreadPoolTaskExecutor-2
ThreadPoolTaskExecutor-2
ThreadPoolTaskExecutor-2
ThreadPoolTaskExecutor-1
ThreadPoolTaskExecutor-3
从结果中可以看得出,线程池执行器变成了“ThreadPoolTaskExecutor”,并且大小为 3。
03、计划任务“二哥,据说 Spring 可以通过 @Scheduled 来实现计划任务,你能给我详细说说怎么实现吗?”
“没问题啊。”