#一 先说一些关键性的东西。
- 当 PoolSize<CorePoolSize 时增加 PoolSize;
- 当队列大小 < QueueCapacity 时由当前线程池执行 workQueue.offer(command);
- 当 PoolSize >= CorePoolSize && PoolSize<MaxPoolSize 时,且队列大小 >=QueueCapacity 时,新增线程数量,但大小必须 < MaxPoolSize.
- KeepAliveTime 是线程是否退出的衡量时间,但核心线程是否退出还要看 allowCoreThreadTimeOut
else if (poolSize > corePoolSize || allowCoreThreadTimeOut)
r = workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS);
#二 下面是重点,Spring 中 ThreadPoolTaskExcutor
##1 异步配置类,为下边的异步注入提供配置
@EnableAsync
@Configuration
@ComponentScan("org.sselab.conf")
public class TaskConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
##2 异步执行类
@Service
public class AsyncTaskService {
@Async //该注解若放到类上,标明该类下所有方法均为异步类。这里的方法自动被注入了ThreadPoolTasjkExcuter
public void excuteAsyncTask(Integer i){
System.out.println("执行异步任务:"+i);
}
@Async
public void excuteAsyncTaskPlus(Integer i){
System.out.println("执行异步任务+1:"+(i+1));
}
}
##3 启动函数
public class AsyncMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskConfig.class);
AsyncTaskService taskService = context.getBean(AsyncTaskService.class);
for (int i = 0; i < 10; i++) {
taskService.excuteAsyncTask(i);
taskService.excuteAsyncTaskPlus(i);
}
context.close();
}
}
4 结果
10:08:22.505 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@617faa95: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,taskConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor,asyncTaskService,org.springframework.scheduling.annotation.ProxyAsyncConfiguration,org.springframework.context.annotation.internalAsyncAnnotationProcessor]; root of factory hierarchy
执行异步任务+1:2
执行异步任务+1:3
执行异步任务+1:1
执行异步任务+1:4
执行异步任务:4
执行异步任务:1
执行异步任务:2
执行异步任务+1:6
执行异步任务:6
执行异步任务+1:7
执行异步任务:7
执行异步任务:3
执行异步任务+1:8
执行异步任务:5
执行异步任务:0
执行异步任务+1:5
执行异步任务+1:10
执行异步任务:9
执行异步任务+1:9
执行异步任务:8
来源:oschina
链接:https://my.oschina.net/u/2861598/blog/785492