1.添加配置类
@Configuration
@EnableAsync
public class AsyncTaskConfig implements AsyncConfigurer {
// ThredPoolTaskExcutor的处理流程
// 当池子大小小于corePoolSize,就新建线程,并处理请求
// 当池子大小等于corePoolSize,把请求放入workQueue中,池子里的空闲线程就去workQueue中取任务并处理
// 当workQueue放不下任务时,就新建线程入池,并处理请求,如果池子大小撑到了maximumPoolSize,就用RejectedExecutionHandler来做拒绝处理
// 当池子的线程数大于corePoolSize时,多余的线程会等待keepAliveTime长时间,如果无请求可处理就自行销毁
@Override
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
//设置核心线程数
threadPool.setCorePoolSize(10);
//设置最大线程数
threadPool.setMaxPoolSize(100);
//线程池所使用的缓冲队列
threadPool.setQueueCapacity(10);
//等待任务在关机时完成--表明等待所有线程执行完
threadPool.setWaitForTasksToCompleteOnShutdown(true);
// 等待时间 (默认为0,此时立即停止),并没等待xx秒后强制停止
threadPool.setAwaitTerminationSeconds(60);
// 线程名称前缀
//threadPool.setThreadNamePrefix("Derry-Async-");
// 初始化线程
threadPool.initialize();
return threadPool;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
一、无返回方式
步骤:
1、写一个类,并且在类或方法上添加注解@Async ,如果在类上添加注解,就代表这个类里所有的方法都是异步执行方法
2、写一个循环方法来调用这个异步方法
@Async
public void asyncTest(int i) {
System.out.println("线程" + Thread.currentThread().getName() + "正在执行任务" + i);
}
二、有返回方式
需要用 Future 来接收
使用AsyncResult<>(T)返回
在Future中:
使用isDone()方法 表明当线程执行完毕后
使用get()方法 表明获取返回结果
@Async
public Future<Long> asyncTest() {
long startTime = new Date().getTime();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = new Date().getTime();
long time = endTime - startTime;
return new AsyncResult(time);
}