其他分享
首页 > 其他分享> > springboot阻塞式异步并发使用

springboot阻塞式异步并发使用

作者:互联网

1.异步线程池配置

@Configuration
@Slf4j
public class TaskPoolConfig {
    @Bean("asyncTaskExcutor")
    public Executor asyncTaskExcutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(5);
        //最大线程数
        executor.setMaxPoolSize(10);
        //队列容量
        executor.setQueueCapacity(50);
        //活跃时间
        executor.setKeepAliveSeconds(100);
        //线程名字前缀
        executor.setThreadNamePrefix("MyExecutor-");
        // setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
        // CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        executor.initialize();
        return executor;
    }
}

2.开启异步以及定义异步方法

@SpringBootApplication
@EnableAsync
public class MyApp {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

}


@Component
@Slf4j
public class AsyncTask {
  
    @Async("asyncTaskExcutor")
    public Future<String> asyncTask2() {
        String threadName=Thread.currentThread().getName();
        long startTime=System.currentTimeMillis();
        log.info("{}开始执行异步方法",threadName);
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("{}结束执行异步方法",threadName);
        long endTIme=System.currentTimeMillis();
        log.info("{}花费时间{}秒",threadName,(endTIme-startTime)/1000);
        return new AsyncResult<>(threadName+"异步任务完成");
    }
}


3.测试

public void testAsync2() {
      List<Future<String>> taskList=new ArrayList<>();
      for (int i = 0; i < 3; i++) {
          Future<String> task = asyncTask.asyncTask2();
          taskList.add(task);
      }
      while (true){
          boolean flag=true;
          for (Future<String> task : taskList) {
              if(!task.isDone()){
                  flag=false;
              }
          }
          if(flag){
              break;
          }
      }
      taskList.forEach(task-> {
          try {
              System.out.println(task.get());
          } catch (InterruptedException e) {
              e.printStackTrace();
          } catch (ExecutionException e) {
              e.printStackTrace();
          }
      });
      System.out.println("主线程调用结束");
  }

标签:异步,task,springboot,threadName,并发,线程,executor,public
来源: https://www.cnblogs.com/ww-NoBugs/p/15824820.html