等待线程池执行完毕后执行后续代码实现的一种方式

线程池配置

@Configuration
@Slf4j
public class BeanConfig {

    /**
     * 执行io操作的线程池
     */
    @Bean
    public ThreadPoolExecutor ioPoolExecutor() {
        AtomicInteger incr = new AtomicInteger(0);
        ThreadFactory threadFactory = runnable -> {
            Thread thread = new Thread(runnable);
            int i = incr.incrementAndGet();
            if (i > 1000) {
                incr.set(0);
                i = incr.incrementAndGet();
            }
            thread.setName("stardust-backend-" + i);
            return thread;
        };
        return new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2 + 1,
                                      Runtime.getRuntime().availableProcessors() * 2 + 1, 1, TimeUnit.MINUTES,
                                      new ArrayBlockingQueue<>(100), threadFactory,
                                      new ThreadPoolExecutor.CallerRunsPolicy());
    }
}

等待线程池

    
    @Autowired
    private ThreadPoolExecutor ioPoolExecutor;

    public Boolean submit(int i) throws InterruptedException {
        int max = 2000,min = 10;
        //线程随机睡眠时间
        int sleepTime = (int) (Math.random()*(max-min)+min);
        Thread.sleep(sleepTime);
        System.out.println("第"+i+"次 执行,睡眠 "+sleepTime+"毫秒");
        return true;
    }

    @Test
    public void test(){

        List<Callable<Boolean>> threadsTaskList = new ArrayList<>();

        for (int i = 0;i < 10 ;i++){

            int finalI = i;
            Callable<Boolean> curTheadTask =
                            () -> {
                                submit(finalI);
                                return true;
                            };
            threadsTaskList.add(curTheadTask);
        }
        try {
            List<Future<Boolean>> futures = ioPoolExecutor.invokeAll(threadsTaskList);
            for (Future<Boolean> future : futures) {
                future.get();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("线程全部执行完毕");
    }

结果输出

第6次 执行,睡眠 23毫秒
第1次 执行,睡眠 64毫秒
第5次 执行,睡眠 141毫秒
第7次 执行,睡眠 279毫秒
第3次 执行,睡眠 1183毫秒
第0次 执行,睡眠 1384毫秒
第2次 执行,睡眠 1425毫秒
第8次 执行,睡眠 1856毫秒
第4次 执行,睡眠 1899毫秒
第9次 执行,睡眠 1939毫秒
线程全部执行完毕

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值