https://blog.csdn.net/zzzgd_666/article/details/82658832
@EnableAsync
@Configuration
class TaskPoolConfig{
@Bean("taskExecutor")
public Executor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
import java.util.Random;
/**
* 异步处理
*
* @author <a href="jian.huang@bintools.cn">yunzhe</a>
* @version 1.0.0 2019-07-09-上午11:19
*/
@Slf4j
@Component
public class Task {
public static Random random = new Random();
@Async("taskExecutor")
public void doTaskOne() throws InterruptedException {
log.info("开始任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务一、耗时:"+(end-start)+"毫秒");
}
@Async("taskExecutor")
public void doTaskTwo() throws InterruptedException {
log.info("开始任务二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务二、耗时:"+(end-start)+"毫秒");
}
@Async("taskExecutor")
public void doTaskThree() throws InterruptedException {
log.info("开始任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务三、耗时:"+(end-start)+"毫秒");
}
}
/***
*
*/
@Component
@Slf4j
public class AsyncTask {
@Async("taskExecutor")
public Future<String> doTask() throws InterruptedException {
log.info("Task1 started");
long start = System.currentTimeMillis();
Thread.sleep(5000);
long end = System.currentTimeMillis();
log.info("Task1 finished,time elapsed:{} ms",end-start);
return new AsyncResult<>("Task1 accomplished");
}
@Async("taskExecutor")
public Future<String> doTask2() throws InterruptedException {
log.info("Task2 started");
long start = System.currentTimeMillis();
Thread.sleep(3000);
long end = System.currentTimeMillis();
log.info("Task2 finished,time elapsed:{} ms",end-start);
return new AsyncResult<>("Task2 accomplished");
}
}