您当前的位置: 首页 >  spring

星夜孤帆

暂无认证

  • 2浏览

    0关注

    626博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Springboot中@Async多线程注解使用

星夜孤帆 发布时间:2020-08-19 19:11:46 ,浏览量:2

@Configuration
@EnableAsync
public class AsyncConfig {
    @Bean("getTaskExector")
    public Executor taskExecutor() {
        //通过Runtime方法来获取当前服务器cpu内核,根据cpu内核来创建核心线程数和最大线程数
        int threadCount = Runtime.getRuntime().availableProcessors();
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadCount);
        executor.setMaxPoolSize(threadCount);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;


@Component
public class Async {
    @Async("getTaskExector")
   public void doTaskThree() throws Exception {
        System.out.println("开始做任务三");
        long start = System.currentTimeMillis();
        Thread.sleep(10000);
        long end = System.currentTimeMillis();
        System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
    }
}
public static void main(String[] args) {

        Async async = new Async();
        for (int i=0;i            
关注
打赏
1636984416
查看更多评论
0.1548s