The Fork/join framework is to solve the problem by using multithreading to realize the divide-and-conquer method. Fork refers to the problem of constantly narrowing the scale, join refers to the results of the calculation of the child problem, to obtain a higher level of results.
The use of the FORK/JOIN framework has certain constraints:
1. In addition to the fork () and join () methods, threads must not use other synchronization tools. Thread is best not to sleep ()
2. Threads must not do I/O operations
3. Threads must not throw checked exception
This framework has several core classes: Forkjoinpool is the thread pool that implements the work-stealing algorithm. Forkjointask is the task class, he has 2 subclasses: Recursiveaction no return value, Recursivetask has a return value, in the definition of their own tasks, usually from the 2 classes, the way to define their own new classes. Because the Forkjointask class implements the Serializable interface, the Serialversionuid attribute should be defined when defining its own task class.
When writing a task, the recommended wording is this:
[Java] view plain copy If (problem size > Default size) {Task s = divide (Task); Execute (tasks); else {resolve problem using another algorithm; }
Forkjoinpool implements the work-stealing algorithm (work-stealing), where threads proactively look for newly created tasks to execute to ensure higher threading utilization. It uses a daemon thread (Deamon) to perform the task, so it is not necessary to close the call shutdown () that he displays. In general, a program needs only one forkjoinpool, so it should be created as follows:
Static final Forkjoinpool Mainpool = new Forkjoinpool (); The number of threads equals the core number of CPUs
Here's a very simple example of a feature that adds 1 to the value of each element in an array. The implementation is: the large array is continuously decomposed into a shorter array, when the length of the sub-array is not more than 10, all elements of which are added 1 operations.
[Java] View Plain copy public class test { public final static ForkJoinPool mainPool = new Forkjoinpool (); public static void main (String[] args) { int n = 26; int[] a = new int[n]; for (int i=0; i<n; i + +) { a[i] = i; } subtask task = new subtask (a, 0, n); mainpool.invoke (Task); for (int i=0; i<n; i++) { system.out.print (a[i]+ " "); } } } class subtask extends RecursiveAction { private static final long serialVersionUID = 1L; private int[] a; private int beg; private int end; public subtask (int[] a, int beg, int end) { &nbsP; super (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;THIS.A = a; this.beg = beg; this.end = end; } @Override protected void compute () { if