ForkJoinPool与递归

1.ForkJoinPool进行文件夹所有文件的记录

static class  MyRecursiveTask extends RecursiveTask<List<String>>{

        private String pathStr;

        public MyRecursiveTask(String pathStr) {
            this.pathStr = pathStr;
        }

        @Override
        protected List<String> compute() {
            List<String> savePathAndFile = new ArrayList<>();
            File homeDir = new File(pathStr);
            if (homeDir.isDirectory()) {
                for (File f : homeDir.listFiles()) {
                    if(f.isDirectory()){
                        MyRecursiveTask taskLeft = new MyRecursiveTask(f.getAbsolutePath());
                        taskLeft.fork();

                        savePathAndFile.addAll(taskLeft.join()) ;
                    }else{
                        savePathAndFile.add(f.getAbsolutePath());
                    }
                }
            }
            return savePathAndFile;
        }
    }

执行线程

  ForkJoinPool fkPool=new ForkJoinPool();
        ForkJoinTask<List<String>> submit = fkPool.submit(new MyRecursiveTask("E:\\xxx\\xx"));
        List<String> strings=null;
        try {
            strings = submit.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            fkPool.shutdown();
        }

普通的递归方法如下

public static List<String>  bfs(String dirPath){
        List<String> savePathAndFile = new ArrayList<>();
        File homeDir = new File(dirPath);
        if (homeDir.isDirectory()) {
            for (File f : homeDir.listFiles()) {
                if(f.isDirectory()){
                    List<String> bfs = bfs(f.getAbsolutePath());
                    savePathAndFile.addAll(bfs);
                }else{
                    savePathAndFile.add(f.getAbsolutePath());
                }
            }
        }
        return savePathAndFile;
    }

main方法执行比较下时间如下,相同的文件目录,该目录下的文件数目为
在这里插入图片描述

556个文件的文件夹的递归遍历是比采用ForkJoinPool快速的
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值