java随记

坚持就是胜利!

 

sbringboot异步执行

把需要异步执行的任务丢到统一的线程池里执行,这个想法不错。springboot简化这个的代码。实现如下:

import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync   //开启异步任务支持
public class TaskExcutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
// TODO Auto-generated method stub
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(20);
taskExecutor.setCorePoolSize(5);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// TODO Auto-generated method stub
return null;
}

任务类或方法

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
//@Async 写在这里则整个类的方法都 是异步执行
@Service
public class AsynTestService {
@Async   //需要异步执行的方法
public void asyncTest() {
for(int i = 0; i < 10;i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

posted on 2017-09-26 12:26 傻 瓜 阅读(289) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(7)

我参与的团队

随笔分类

随笔档案

文章分类

友情链接

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜