
http://www.javacreed.com/java-fork-join-example/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
public class extends RecursiveTask<Long> { private File file; private (File f){ this.file = f; } protected Long compute() { if(file.isFile()){ System.out.println(file.getAbsolutePath()); return file.length(); } List<MyTask> tasks =new ArrayList<>(); File[] files = file.listFiles(); for(File f : files){ MyTask task = new MyTask(f); task.fork(); tasks.add(task); } long size = 0; for(MyTask myTask: tasks){ size = size+myTask.join(); } return size; } public static void main(String[] args) { ForkJoinPool pool =new ForkJoinPool(); try{ Long length =pool.invoke(new MyTask(new File("/Users/zheng/Documents/mt_workspace/"))); System.out.println("得到的文件大小为"+ length); }catch (Exception ex){ ex.printStackTrace(); }finally { pool.shutdown(); } } }
|
Fork/Join在分配任务时,不是很合理.想知道为啥不?赶紧看看文章讲解吧!!!
近期评论