如何使用ExecuterService划分线程?

时间:2015-11-30 06:24:03

标签: java multithreading java.util.concurrent

我有一个大约有5000个对象的数组。对于每个对象,我计划执行一些逻辑。每个对象的逻辑是相同的。我想尽可能快地完成它,所以我来到了ExecutorService,它位于java.util.cuncurrent中。我决定在一个线程中使用100个对象,所以我将总数(~5k)分成间隔

private List<Integer> divideIntoIntervals(Integer total)
{
    List<Integer> intervals = new ArrayList<Integer>();
    intervals.add(0);
    int n = total / PART_SIZE;

    int leftover = total % PART_SIZE;
    if(n!=0)
    {
        intervals.add(PART_SIZE);
        for (int i=2; i<=n; i++)
        {
            intervals.add(PART_SIZE*i);
        }
        intervals.add(PART_SIZE*n+leftover);
    }

    return intervals;
}

所以,数组将是:0,100,200,300,...,5000,5041。 您会建议哪些cuncurrent列表? 我计划创建逻辑,它在另一个时间间隔内寻找我的cuncurrent数组。

2 个答案:

答案 0 :(得分:2)

您可能不需要并发列表。只要您在线程完成工作时不修改列表,您就可以创建一个单独的Runnable,它可以在自己的范围内工作,并将这些可运行的数据提交给具有相应数量的ThreadPoolExecutorService的{​​{1}}线程(在你的情况下约为50)。任务将自动在线程之间均匀分配:

ExecutorService executor = Executors.newFixedThreadPool(list.size() / 100 + 1);
// (+1 in case there are less than 100 items)
for (int i = 0; i < list.size(); i += 100) {
    final int start = i;
    executor.execute(() -> {
        int end = start + 100;
        if (end > list.size()) {
            end = list.size();
        }
        for (int j = start; j < end; ++j) {
            list.get(j).doYourLogicHere();
        }
    });
}

如果您不完全确定不会在这些任务之外修改列表,则应根据您想要处理这些修改来更改代码。例如,如果在处理过程中可以将新项目附加到列表中,并且您不关心在此阶段是否处理这些新项目,那么您可能希望使用CopyOnWriteArrayList并更改上面的内部循环使用迭代器而不是基于int的索引。这将导致代码在创建迭代器时使用列表的快照(如果迭代时没有修改,则不会进行任何实际复制)。根据新项目的追加时间,此快照可能包括也可能不包含它们,但至少它会保持一致并且不会中断。

答案 1 :(得分:2)

您还可以使用newCachedThreadPool方法。这将创建一个线程池,根据需要创建新线程,但会在可用时重用以前构造的线程。 Source

我如何使用它的示例:

        //  Create an executor service with  a thread pool that creates new threads as needed,
        //  but will reuse previously constructed threads when they are available
        ExecutorService executorService = Executors.newCachedThreadPool();

        Integer finalMinValue = minValue;
        Integer finalMaxValue = maxValue;

        executorService.execute(() -> {
            // Initialise buckets
            int bucketCount = (finalMaxValue - finalMinValue) / bucketSize + 1;
            List<List<Integer>> buckets = new ArrayList<>(bucketCount);

            for (int i = 0; i < bucketCount; i++) {
                buckets.add(new ArrayList<>());
            }


            // Distribute input array values into buckets
            for (Integer anArrayElement : arrayToSort) {
                buckets.get((anArrayElement - finalMinValue) / bucketSize).add(anArrayElement);

            }

            //  Sort buckets and place back into input array
            //  Loop through the contents of each bucket
            for (List<Integer> bucket : buckets) {


                Integer[] bucketArray = new Integer[bucket.size()];

                bucketArray = bucket.toArray(bucketArray);

                InsertionSort.sort(bucketArray);

                for (Integer aBucketArray : bucketArray) {
                    arrayToSort[currentIndex] = aBucketArray;
                    incrementSync();
                }
            }
        });

有关此实施的更多信息,请参阅Github