Java线程池: 等待所有线程执行完成

场景

需要获取多个结果, 并进行运算, 想通过线程池增加结果获取速度, 且所有结果获取后, 可以继续计算并统一返回。

依赖



    com.google.guava
    guava
    30.1-jre

  • 使用Java8

代码

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class thread {

    public static void main(String[] args) throws InterruptedException {
        // 定义线程名字,方便回溯
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("test-pool-%d").build();
        // 手动创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 0, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue(1024),
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy());

        // 调用线程池执行任务
        List list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.execute(() -> {
                try {
                    String test = getTest();
                    list.add(test);
                    System.out.println(test);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("执行线程.." + Thread.currentThread().getName());
            });
        }

        // 所有任务执行完成且等待队列中也无任务关闭线程池
        threadPoolExecutor.shutdown();
        // 阻塞主线程, 直至线程池关闭
        threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);


        System.out.println("========================");
        System.out.println("=======主线程执行完了======");
        System.out.println("========================");

        System.out.println(list);


    }

    static String getTest() throws InterruptedException {
        Random random = new Random();
        int i = random.nextInt(3000);
        Thread.sleep(i);
        return "hello" + i;
    }

}

执行结果

hello281
执行线程..test-pool-2
hello550
执行线程..test-pool-3
hello671
执行线程..test-pool-4
hello1041
执行线程..test-pool-1
hello813
执行线程..test-pool-3
hello981
执行线程..test-pool-1
hello735
执行线程..test-pool-3
hello1622
执行线程..test-pool-4
hello2393
执行线程..test-pool-0
hello2333
执行线程..test-pool-2
========================
=======主线程执行完了======
========================
[hello281, hello550, hello671, hello1041, hello813, hello981, hello735, hello1622, hello2393, hello2333]

Process finished with exit code 0

你可能感兴趣的:(java-web,多线程,thread,并发编程,阻塞)