赞
踩
1.配置线程类
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@ComponentScan("@Async 注解所在类的包路径")
@EnableAsync // 利用@EnableAsync注解开启异步任务支持
public class AsyncTaskConfig {
@Bean("taskExecutor")
public Executor asyncExecutor() { // 配置类实现AsyncConfigurer接口并重写 getAsyncExecutor 方法,并返回一个 ThreadPoolTaskExecutor,这样我们就获得了一个线程池 taskExecutor
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(30);
taskExecutor.setMaxPoolSize(2000);
taskExecutor.setQueueCapacity(200);
taskExecutor.setKeepAliveSeconds(60);
taskExecutor.initialize();
return taskExecutor;
}
}
2.编写异步任务方法
@Async("taskExecutor") // 通过@Async注解表明该方法是一个异步方法,如果注解在类级别,表明该类下所有方法都是异步方法,而这里的方法自动被注入使用ThreadPoolTaskExecutor 作为 TaskExecutor
public void executeAsyncTaskAll(CountDownLatch latch){
try {
log.info("taskExecutor end.")
} catch (Exception e) {
e.printStackTrace();
} finally {
latch.countDown();//线程数-1
}
}
3.编写调用方法
final CountDownLatch latch = new CountDownLatch("int类型,线程数");
for (int i = 0; i <300; i += 100) {
//3.多线程任务
executeAsyncTaskAll(latch);
}
try {
latch.await();//等待CountDownLatch 为0并发执行
} catch (InterruptedException e) {
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。