java的异步回调技术

上一次看见这玩意,还不知道它就是异步回调,错误理解为多线程的方式,其实都差不多,交给线程处理,主线程搜集数据:

package com.quxiao.controller;


import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.*;
import java.util.stream.LongStream;

/**
 * @program: package1
 * @author: quxiao
 * @create: 2023-09-27 15:22
 **/
public class t3 {
    static final ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) throws Exception {
        //五条线程,0-1000000计数,随机
        CompletableFuture future1 = CompletableFuture.supplyAsync(() -> {
            long sum = 0;
            long r = new Random().nextInt(100000000) + 50000000;
            //stream并行流
            sum = LongStream.rangeClosed(0, r).parallel().sum();
            return sum;
        }, executor);
        CompletableFuture future2 = CompletableFuture.supplyAsync(() -> {
            long sum = 0;
            long r = new Random().nextInt(100000000) + 50000000;
            sum = LongStream.rangeClosed(0, r).parallel().sum();
            return sum;
        }, executor);
        CompletableFuture future3 = CompletableFuture.supplyAsync(() -> {
            long sum = 0;
            long r = new Random().nextInt(100000000) + 50000000;
            sum = LongStream.rangeClosed(0, r).parallel().sum();
            return sum;
        }, executor);
        CompletableFuture future4 = CompletableFuture.supplyAsync(() -> {
            long sum = 0;
            long r = new Random().nextInt(100000000) + 50000000;
            sum = LongStream.rangeClosed(0, r).parallel().sum();
            return sum;
        }, executor);
        CompletableFuture future5 = CompletableFuture.supplyAsync(() -> {
            long sum = 0;
            long r = new Random().nextInt(100000000) + 50000000;
            sum = LongStream.rangeClosed(0, r).parallel().sum();
            return sum;
        }, executor);
        CompletableFuture.allOf(future1, future2, future3, future4, future5);
        System.out.println(future1.get());
        System.out.println(future2.get());
        System.out.println(future3.get());
        System.out.println(future4.get());
        System.out.println(future5.get());
        executor.shutdown();
    }
}

你可能感兴趣的:(多线程,java,python,前端)