springboot 开启多个线程

介绍

一些接口操作可以毕竟费时,而tomact线程的数量又是有限的,想要提高web吞吐量可以在spring里开启异步。spring默认的线程是有限的(反正默认的不太好之类的),需要自己手工配置个线程池效果会更好。

@Configuration
@EnableAsync//开启对异步任务的支持
public class ThreadAsyncConfigurer  implements AsyncConfigurer {
  @Bean
  public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
    //设置核心线程数
    threadPool.setCorePoolSize(10);
    //设置最大线程数
    threadPool.setMaxPoolSize(100);
    //线程池所使用的缓冲队列
    threadPool.setQueueCapacity(10);
    //等待任务在关机时完成--表明等待所有线程执行完
    threadPool.setWaitForTasksToCompleteOnShutdown(true);
    // 等待时间 (默认为0,此时立即停止),并没等待xx秒后强制停止
    threadPool.setAwaitTerminationSeconds(60);
    //  线程名称前缀
    threadPool.setThreadNamePrefix("MyAsync-");
    // 初始化线程
    threadPool.initialize();
    return threadPool;
  }

  @Override
  public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    return null;
  }

}

使用就很方便 在接口上加上@Async,如果加在类上则表示该类的所有接口都是异步的

@Service
public class AsyncTaskService {
  @Async
  public void executeAsyncTask(Integer n){
    System.out.println("异步任务执行:"+n);
  }


  @Async
  public void executeAsyncTaskPlus(Integer n){
    System.out.println("异步任务执行+1:"+(n+1));
  }
}


----------------------------------------------------

还有就是在一个springbean中使用多线程进行传入的数据处理可以这样做。

@Component
@Slf4j
public class DealThreadTask {

  private ExecutorService fixedThreadPool;

  //初始化线程池
  @PostConstruct
  public void init() {
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(6);
    this.fixedThreadPool = fixedThreadPool;
  }

  public void execute(String name) {
    for (int j = 1; j < 3; j++) {
      List<TestLcc> testLccList = new ArrayList<>();

      for (int i = 1; i < 3; i++) {
        testLccList.add(new TestLcc(i, name + i, (int) (Math.random() * 100)));
      }

      MoniotrTask moniotrTask = new MoniotrTask(testLccList, name + "线程" + j);
      if (!fixedThreadPool.isShutdown()) {
        fixedThreadPool.execute(moniotrTask);
      }
    }
  }

  public class MoniotrTask implements Runnable {
    private List<TestLcc> lccList;
    private String name;
    private Connection connection;

    public MoniotrTask(List<TestLcc> lccList, String name) {
      this.lccList = lccList;
      this.name = name;
    }

    @Override
    public void run() {
      System.out.println("启动" + name + "线程");
      for (int i = 0; i < lccList.size(); i++) {
        System.out.println(lccList.get(i).toString());
      }
    }

  }


}


  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值