The commonPool() method in the ForkJoinPool class returns the common pool of ForkJoinPool instances.

The common pool is a shared pool of worker threads that can be used for executing ForkJoinTask instances. It is designed to provide a simple and efficient way to parallelize computation in a Fork/Join framework.

The common pool is created lazily when it is first accessed, and its size is determined by the available processors on the system. By default, the common pool has its parallelism level set to the number of available processors, but this can be changed using the java.util.concurrent.ForkJoinPool.common.parallelism system property.

To use the common pool, you can submit ForkJoinTask instances to it using the execute() or submit() methods. The common pool will automatically schedule and execute the tasks on its worker threads.

Here is an example of using the commonPool() method:

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ExampleTask extends RecursiveTask<Integer> {
    private final int threshold = 10;
    private int[] array;
    private int start;
    private int end;

    public ExampleTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if (end - start <= threshold) {
            int sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            return sum;
        } else {
            int mid = (start + end) / 2;
            ExampleTask leftTask = new ExampleTask(array, start, mid);
            ExampleTask rightTask = new ExampleTask(array, mid, end);
            leftTask.fork();
            rightTask.fork();
            return leftTask.join() + rightTask.join();
        }
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        ExampleTask task = new ExampleTask(array, 0, array.length);
        ForkJoinPool.commonPool().invoke(task);
        System.out.println(task.join());
    }
}

In this example, we create a RecursiveTask called ExampleTask that calculates the sum of an array of integers. We divide the array into smaller sub-arrays and use the common pool to parallelize the computation. The commonPool().invoke(task) method is used to submit the task to the common pool, and the task.join() method is used to obtain the result of the computation

ForkJoinPool#commonPool

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

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