加入收藏 | 设为首页 | 会员中心 | 我要投稿 宁德站长网 (https://www.0593zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

Java借助多线程计算目录数据大小

发布时间:2021-11-20 19:47:02 所属栏目:教程 来源:互联网
导读:1 顺序扫描 提到计算目录数据大小,我们首先想到的会是顺序遍历每个文件,并累加遍历后的结果。如下面例子,该例子使用顺序计算目录大小的方法。 public class TotalFileSizeSequential{ private long getTotalSizeOfFileInDir(final File file){ if(file.isF
1 顺序扫描
 
提到计算目录数据大小,我们首先想到的会是顺序遍历每个文件,并累加遍历后的结果。如下面例子,该例子使用顺序计算目录大小的方法。
 
public class TotalFileSizeSequential{
    private long getTotalSizeOfFileInDir(final File file){
        if(file.isFile()){
              return file.length();
        }
        final File[] children = file.listFile();
        if(children!=null){
            for(final File child:children){
                total += getTotalSizeOfFileInDir(child);//递归遍历
          }
        }
        return total
    }
 
    public void static main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next(); //输入目录
 
        final long start = System.nanoTime();
        final long total = new TotalFileSizeSequential().getTotalSizeOfFilesInDir(new File(str));
        final long end = System.nanoTime();
 
        System.out.println("文件总大小 " + total);
        System.out.println("所用时间 " + (end-start)/1.0e9);
    }
}
 
2 线程不安全扫描
 
从上面例子可以看出,这里并为使用了多线程来进行计算,而是按照执行顺序来累加结果。虽然结果是正确的,但却不是高效的。所以接下来我们使用多线程的一个例子,但该例子遇到了一个问题,那就是线程死锁问题,先看下再进行具体分析:
 
public class NavelyConcurrentTotalFileSize{
    private long getTotalSizeOfFileInDir(ExecutorService service,File file)
                    throws InterruptedException,ExecutionException,TimeoutException{
          if(file.isFile()){
              return file.length();
          }
          long total = 0;
          final File[] children = file.listFile();
 
          if(children != null){
              final List<Future<Long>> partialTotalFuture = new ArrayList<Future<Long>>();
              for(final File child:children){
                  partialTotalFuture.add(service.submit(new Callable<Long>{ //执行任务
                        public Long call() throws InterruptedException,
                                      ExecutionException,TimeoutException{
                              return getTotalSizeOfFilesInDir(service,child);
                        }
                  }));
              }
              for(Future<Long> partialTotalFuture:partialTotalFutures){
                    total += partialTotalFuture.get(100,TimeUnit.SECODES);//计算结果
              }
          }
        return tatal;
    }
 
    private long getTotalSizeOfFile(string fileName) throws InterruptedException,
                ExecutionException,TimeoutException{
        ExecutorService service = Executors.newFixedThreadPool(100);
        try{
            return getTotalSizeOfFileInDir(service,new File(fileName));
        }finally{
            service.shutdown();
        }
    }
 
        public void static main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next(); //输入目录
 
        final long start = System.nanoTime();
        final long total = new NaivelyConcurrentTotalFileSize().getTotalSizeOfFile(str);
        final long end = System.nanoTime();
 
        System.out.println("文件总大小 " + total);
        System.out.println("所用时间 " + (end-start)/1.0e9);
    }
 
}
 
上面的这个例子开启了一个100大小的线程池,并在Future执行结果的时候设定了运行时间,超过运行时间将抛出异常。这里,当我们的目录没那么多文件的时候,并不存在问题,但当目录包含很大文件的时候,此时每当遇到一个子目录,就通过service.submit执行任务,既把改任务调度给其他线程,照如此下去,当我们还未深入到最底层目录时,由于线程数目的限制,导致线程池内的等待某些任务的相应,而这些任务却在ExcotorService的队列中等待执行的机会,因为线程是递归的,即从最外层到最里层,所以在等待最里层返回结果,但是最里层又没有额外的线程来执行,于是形成死锁状态。最后因为设置了超时,避免程序处于假死状态。

(编辑:宁德站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读