当前位置:   article > 正文

spring boot中多线程并发及利用CountDownLatch并发执行多线程_springboot countdownlatch

springboot countdownlatch

1.配置线程类

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@ComponentScan("@Async 注解所在类的包路径")
@EnableAsync // 利用@EnableAsync注解开启异步任务支持
public class AsyncTaskConfig  {
    @Bean("taskExecutor")
    public Executor asyncExecutor() { // 配置类实现AsyncConfigurer接口并重写 getAsyncExecutor 方法,并返回一个 ThreadPoolTaskExecutor,这样我们就获得了一个线程池 taskExecutor
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(30);
        taskExecutor.setMaxPoolSize(2000);
        taskExecutor.setQueueCapacity(200);
        taskExecutor.setKeepAliveSeconds(60);
        taskExecutor.initialize();
        return taskExecutor;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

2.编写异步任务方法

    @Async("taskExecutor") // 通过@Async注解表明该方法是一个异步方法,如果注解在类级别,表明该类下所有方法都是异步方法,而这里的方法自动被注入使用ThreadPoolTaskExecutor 作为 TaskExecutor
    public void executeAsyncTaskAll(CountDownLatch latch){
        try {
            log.info("taskExecutor end.")
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            latch.countDown();//线程数-1
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3.编写调用方法

final CountDownLatch latch = new CountDownLatch("int类型,线程数");
for (int i = 0; i <300; i += 100) {
   //3.多线程任务
   executeAsyncTaskAll(latch);
}
try {
   latch.await();//等待CountDownLatch  为0并发执行
} catch (InterruptedException e) {
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/52470
推荐阅读
相关标签
  

闽ICP备14008679号