spring boot中多线程并发及利用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;
    }
}

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
        }
    }

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) {
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值