以下是一种可能的实现方式:

import java.util.concurrent.*;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        int[] arr = {1, 5, 3, 9, 7, 6, 8, 4, 2, 10}; // 待处理的数组
        ExecutorService executorService = Executors.newFixedThreadPool(3); // 创建线程池,大小为3
        Future<Integer>[] futures = new Future[3]; // 用于保存线程执行结果的Future数组
        int len = arr.length / 3; // 每个线程处理的数组长度
        for (int i = 0; i < 3; i++) {
            int start = i * len;
            int end = (i == 2) ? arr.length : (i + 1) * len; // 最后一个线程处理剩余的部分
            futures[i] = executorService.submit(new MaxFinder(arr, start, end)); // 提交任务给线程池
        }
        int max = Integer.MIN_VALUE; // 最大值
        for (int i = 0; i < 3; i++) {
            try {
                int result = futures[i].get(); // 阻塞等待线程执行结果
                if (result > max) {
                    max = result;
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.println('最大值为:' + max);
        executorService.shutdown(); // 关闭线程池
    }
}

class MaxFinder implements Callable<Integer> {
    private int[] arr;
    private int start;
    private int end;

    public MaxFinder(int[] arr, int start, int end) {
        this.arr = arr;
        this.start = start;
        this.end = end;
    }

    @Override
    public Integer call() throws Exception {
        int max = Integer.MIN_VALUE;
        for (int i = start; i < end; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        return max;
    }
}

上述代码中,我们通过ExecutorService创建了一个大小为3的线程池,然后将待处理的数组分成了3份,每个线程处理其中一份,利用Callable接口实现了线程任务,返回该部分的最大值。然后我们用一个Future数组保存每个线程的执行结果,最后遍历一遍结果,求得整个数组的最大值。需要注意的是,我们在获取Future结果时使用了get方法,这个方法会阻塞等待线程执行完毕并返回结果,因此需要放在一个try-catch块中处理异常。最后,我们通过调用shutdown方法关闭了线程池。

通过使用线程池,我们可以将大型数组的处理任务分配给多个线程并行执行,从而显著提升效率。这种方法在处理大规模数据时特别有效。

Java线程池优化:高效分割数组并查找最大值

原文地址: https://www.cveoy.top/t/topic/ogIE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录