Java concurrency tool class ForkJoin task decomposition, tool class forkjoin
Introduction to the Fork/Join framework
Step 1: Split the task. First, we need a fork class to split large tasks into subtasks. It is possible that the subtasks are still large, so we still need to keep splitting until the subtasks are small enough.
Step 2: Execute the task and merge the results. Separate sub-tasks are placed in the double-end queue, and then several start threads obtain the task execution from the double-end queue respectively. All the results of sub-tasks are stored in a queue. Start a thread to fetch data from the queue and merge the data.
Fork/Join uses two classes to accomplish the preceding two tasks:
- ForkJoinTask: to use the ForkJoin framework, you must first create a ForkJoin task. It provides a mechanism to execute fork () and join () operations in a task. Generally, we do not need to inherit the ForkJoinTask class directly, but only need to inherit its subclass, the Fork/Join framework provides the following two subclasses:
- RecursiveAction: used for tasks that do not return results.
- RecursiveTask: used for tasks with returned results.
- ForkJoinPool: ForkJoinTask needs to be executed through ForkJoinPool. The child tasks separated by the tasks are added to the dual-end queue maintained by the current working thread and enter the queue header. When no task exists in the queue of a worker thread, it randomly obtains a task from the tail of the queue of other worker threads.
1 package com. thread. test. thread; 2 3 import java. io. file; 4 import java. util. arrayList; 5 import java. util. list; 6 import java. util. concurrent. forkJoinPool; 7 import java. util. concurrent. recursiveTask; 8 9/** 10 * Created by windwant on 2016/6/3. 11 */12 public class MyForkJoin {13 14 public static void main (String [] args) {15 MyTask task = new MyTask (new File ("D: \ MPS "); 16 Integer sum = new ForkJ OinPool (). invoke (task); 17 System. out. println (sum); 18} 19} 20 21 class MyTask extends RecursiveTask <Integer> {22 23 public Integer num = 0; 24 25 private File file; 26 MyTask (File file) {27 this. file = file; 28} 29 30 @ Override31 protected Integer compute () {32 List <MyTask> taskList = new ArrayList <MyTask> (); 33 if (file. isDirectory () {34 File [] list = file. listFiles (); 35 for (File subf: list) {36 if (subf. I SDirectory () {37 MyTask mt = new MyTask (subf); 38 taskList. add (mt); 39} else {40 num ++; 41} 42} 43} else {44 num = 1; 45} 46 47 if (! TaskList. isEmpty () {48 // same as 49 // for (MyTask mtask: taskList) {50 // mtask. fork (); 51 //} 52 // for (MyTask mtask: taskList) {53 // num + = mtask. join (); 54 //} 55 56 for (MyTask mtask: invokeAll (taskList) {57 num + = mtask. join (); 58} 59} 60 return num; 61} 62}
Project address: https://github.com/windwant/threadtest