Home >Java >javaTutorial >How to use the Fork/Join framework for parallel programming in Java concurrent programming?
How to use Java Fork/Join framework for parallel programming? Create a task class and implement the RecursiveAction or RecursiveTask interface. Create Fork/Join pool and manage task execution. Call the fork() method to submit the task to the pool and decompose it into subtasks. Call the join() method to wait for the task to complete and get the results (for RecursiveTask).
Java Concurrent Programming: Parallel Programming Using the Fork/Join Framework
The Fork/Join Framework is a Java library that provides A lightweight framework for efficiently executing parallel tasks. It is based on a work-stealing algorithm that enables threads to collaborate on tasks, thereby maximizing utilization of CPU resources.
How to use the Fork/Join framework:
java.util. concurrent.RecursiveAction
or java.util.concurrent.RecursiveTask
interface. RecursiveAction is used to perform tasks that do not return a value, while RecursiveTask does. java.util.concurrent.ForkJoinPool
to create a thread pool. It will manage the execution of Fork/Join tasks. fork()
method to submit the task to the Fork/Join pool. The pool breaks tasks into smaller subtasks and assigns them to available threads. join()
method to wait for the task to complete. For RecursiveTask, it also returns the return value to the main thread. Practical case:
Suppose we have a parallel task that calculates the sum of all odd numbers in a list of numbers. We can implement this using the Fork/Join framework as follows:
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction; public class OddSumTask extends RecursiveAction { private int[] numbers; private int start; private int end; public OddSumTask(int[] numbers, int start, int end) { this.numbers = numbers; this.start = start; this.end = end; } @Override protected void compute() { int sum = 0; for (int i = start; i < end; i++) { if (numbers[i] % 2 != 0) { sum += numbers[i]; } } System.out.println("Partial sum: " + sum); } } public class Main { public static void main(String[] args) { // 创建一个数字列表 int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // 创建一个 Fork/Join 池 ForkJoinPool pool = new ForkJoinPool(); // 创建一个 OddSumTask OddSumTask task = new OddSumTask(numbers, 0, numbers.length); // Fork 任务 pool.invoke(task); } }
Running this code will add the odd numbers in the list and print out the local sum calculated by each thread.
The above is the detailed content of How to use the Fork/Join framework for parallel programming in Java concurrent programming?. For more information, please follow other related articles on the PHP Chinese website!