java 并行计算 并行执行多任务 多线程并行计算 线程池封装 并行池

package main.java.work;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
class parallelPool {
    ExecutorService executor;
    CountDownLatch latch;
    int taskCount;
    List<Runnable> taskList;
    public parallelPool() {
        /*
        poolSize:线程池数量
         */
         //int THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2; // 24
         //System.out.println(THREAD_POOL_SIZE);
        this.executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        this.taskCount = 0;
        //  this.taskList = Collections.synchronizedList(new ArrayList<>());
        this.taskList =  new ArrayList<>();
    }
    public parallelPool(int poolSize) {
        /*
        poolSize:线程池数量
         */
        this.executor = Executors.newFixedThreadPool(poolSize);
        this.taskCount = 0;
        //  this.taskList = Collections.synchronizedList(new ArrayList<>());
        this.taskList =  new ArrayList<>();
    }
    public void submit(Runnable task){
        this.taskCount += 1;
        this.taskList.add(task);
    }
    private void run(){
        this.latch = new CountDownLatch(this.taskCount);
        for(int i=0;i<this.taskCount;i++) {
            int finalI = i;
            this.executor.submit(() -> {
                try {
                    taskList.get(finalI).run();
                } finally {
                    latch.countDown();
                }
            });
        }
    }
    public void awaitCompletion () throws InterruptedException{
        this.run();
        this.latch.await();
        this.executor.shutdown();
    }
}

public class ParallelFibonacci {
    // 斐波那契计算函数
    private static long fibonacci(int n) {
        if (n <= 1) return n;
        return fibonacci(n-1) + fibonacci(n-2);
    }

    public static void main(String[] args) throws InterruptedException {

//        int poolSize = 12;
//        ExecutorService executor = Executors.newFixedThreadPool(12);
//        int taskCount = 44; // 计算斐波那契数列的前40项
//        // 使用Collections进行封装,才能使并发list线程安全
//        List<Long> rlt = Collections.synchronizedList(new ArrayList<>());
//
//        //计数引用可使并发计算等等结束在执行后面任务
//        //ConcurrentHashMap<String, Integer> safeMap = new ConcurrentHashMap<>();
//
//
//        CountDownLatch latch = new CountDownLatch(taskCount);
//
//        // 提交斐波那契计算任务
//        for (int i = 0; i < taskCount; i++) {
//            final int n = i;
//            executor.submit(() -> {
//                rlt.add(fibonacci(n));
//                latch.countDown();  // 任务完成计数器减1
////                long startTime = System.nanoTime();
////                long result = fibonacci(n);
////                long duration = (System.nanoTime() - startTime) / 1_000_000;
////                System.out.printf("Fibonacci(%d) = %d (计算耗时: %d ms) [线程: %s]%n",
////                        n, result, duration, Thread.currentThread().getName());
//            });
//        }
//
//
//        // 关闭线程池
//        latch.await();  // 阻塞直到所有任务完成
//        executor.shutdown(); //关闭线程池
//
//        System.out.println(rlt);
//
//        System.out.println(rlt.size());


        parallelPool execution = new parallelPool();

        // 使用 Collections 保证线程安全
        List<Long> rlt1 = Collections.synchronizedList(new ArrayList<>());

        //使用ConcurrentHashMap 保证并行线程安全
         //ConcurrentHashMap<String, Integer> safeMap = new ConcurrentHashMap<>();
        int m = 46;
        for(int i=0;i<m;i++) {
            final int n = i;
            execution.submit(() -> {
                rlt1.add(fibonacci(n));
            });
        }

        execution.submit(() -> {rlt1.add(fibonacci(45));});
        execution.submit(() -> {rlt1.add(fibonacci(46));});

        execution.submit(() -> {rlt1.add(fibonacci(45));});
        execution.submit(() -> {rlt1.add(fibonacci(46));});

        execution.awaitCompletion();

        System.out.println(rlt1);

        System.out.println(rlt1.size());


    }
}
posted @ 2025-09-04 23:50  ARYOUOK  阅读(13)  评论(0)    收藏  举报