java隨記

          堅持就是勝利!

           

          sbringboot異步執(zhí)行

          把需要異步執(zhí)行的任務(wù)丟到統(tǒng)一的線程池里執(zhí)行,這個想法不錯。springboot簡化這個的代碼。實(shí)現(xiàn)如下:

          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   //開啟異步任務(wù)支持
          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;
          }

          任務(wù)類或方法

          import org.springframework.scheduling.annotation.Async;
          import org.springframework.stereotype.Service;
          //@Async 寫在這里則整個類的方法都 是異步執(zhí)行
          @Service
          public class AsynTestService {
          @Async   //需要異步執(zhí)行的方法
          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 傻 瓜 閱讀(310) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           

          導(dǎo)航

          統(tǒng)計

          常用鏈接

          留言簿(7)

          我參與的團(tuán)隊(duì)

          隨筆分類

          隨筆檔案

          文章分類

          友情鏈接

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 海伦市| 磐石市| 彭山县| 聂荣县| 陇南市| 台江县| 宁阳县| 乃东县| 黄骅市| 涪陵区| 凌云县| 府谷县| 东台市| 浏阳市| 禄丰县| 佛坪县| 咸阳市| 锦州市| 托克托县| 鸡东县| 集安市| 收藏| 乌鲁木齐县| 镇平县| 临高县| 纳雍县| 云安县| 温州市| 社会| 南澳县| 常德市| 苏尼特左旗| 元朗区| 定南县| 屯门区| 乌鲁木齐县| 卢湾区| 汕尾市| 萨嘎县| 大港区| 定州市|