java项目利用线程池,同时执行多个需求,返回数据,加快速度

使用线程池还是挺快的,提升了50%左右

package com.quxiao.controller;

import com.alibaba.fastjson2.JSON;
import lombok.Data;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @program: package1
 * @author: quxiao
 * @create: 2023-09-11 15:10
 **/
public class t2 {
    public static void main(String[] args) {
//        long l = System.currentTimeMillis();
//        for (int i = 0; i < 10; i++) {
//            check();
//        }
//        System.out.println("顺序执行耗时:" + (System.currentTimeMillis() - l));
        ExecutorService executor =  Executors.newFixedThreadPool(10);
        long l = System.currentTimeMillis();
        //顺序执行耗时:11600
        CompletableFuture async1 = CompletableFuture.supplyAsync(() -> check(), executor);
        System.out.println("1");
        CompletableFuture async2 = CompletableFuture.supplyAsync(() -> check(), executor);
        System.out.println("1");
        CompletableFuture async3 = CompletableFuture.supplyAsync(() -> check(), executor);
        System.out.println("1");
        CompletableFuture async4 = CompletableFuture.supplyAsync(() -> check(), executor);
        System.out.println("1");
        CompletableFuture async5 = CompletableFuture.supplyAsync(() -> check(), executor);
        System.out.println("1");
        CompletableFuture async6 = CompletableFuture.supplyAsync(() -> check(), executor);
        System.out.println("1");
        CompletableFuture async7 = CompletableFuture.supplyAsync(() -> check(), executor);
        System.out.println("1");
        CompletableFuture async8 = CompletableFuture.supplyAsync(() -> check(), executor);
        System.out.println("1");
        CompletableFuture async9 = CompletableFuture.supplyAsync(() -> check(), executor);
        System.out.println("1");
        CompletableFuture async10 = CompletableFuture.supplyAsync(() -> check(), executor);
        System.out.println("1");
        //确认所有的数据都已经处理完了
        CompletableFuture.allOf(async1, async2, async3, async4, async5, async6, async7, async8, async9, async10).join();
        System.out.println("1");
        System.out.println("顺序执行耗时:" + (System.currentTimeMillis() - l));
    }

    private static String check() {
        for (int j = 0; j < 50000000; j++) {
            String s = "" + j + j;
        }
        return "ok";
    }
}

你可能感兴趣的:(java,python,算法)