java并发编程学习之ForkJoin-框架RecursiveAction三

43次阅读

共计 1095 个字符,预计需要花费 3 分钟才能阅读完成。

通过 RecursiveAction 复制文件

public class MoveFiles extends RecursiveAction {
    private File path;
    /**
     * 源文件夹
     */
    static String SOURCE_URL = "G:\\workspaces2";
    /**
     * 目标文件夹
     */
    static String TARGET_URL = "H:\\test";


    public MoveFiles(File path) {this.path = path;}

    @Override
    protected void compute() {List<MoveFiles> subTasks = new ArrayList<>();

        File[] files = path.listFiles();
        if (files != null) {for (File file : files) {String absolutePath = file.getAbsolutePath();
                String targetDir = absolutePath.replace(SOURCE_URL, TARGET_URL);
                File targetPath = new File(targetDir);
                if (file.isDirectory()) {targetPath.mkdirs();
                    subTasks.add(new MoveFiles(file));
                } else {
                    try {Files.copy(file.toPath(), targetPath.toPath());
                    } catch (IOException e) {e.printStackTrace();
                    }
                }
            }
            if (!subTasks.isEmpty()) {for (MoveFiles subTask : invokeAll(subTasks)) {subTask.join();
                }
            }
        }
    }

    public static void main(String[] args) {
        try {ForkJoinPool pool = new ForkJoinPool();
            MoveFiles task = new MoveFiles(new File(SOURCE_URL));
            pool.execute(task);
            long start = System.currentTimeMillis();
            System.out.println("任务开始");
            task.join();
            long end = System.currentTimeMillis();
            System.out.println("任务结束,耗时:" + (end - start) / 1000);
        } catch (Exception e) {e.printStackTrace();
        }
    }
}

正文完
 0