首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java 计算文件目录上文件总大小的几种多线程并发实现

2012-11-26 
java 计算文件目录下文件总大小的几种多线程并发实现1.单线程实现package com.mimeimport java.io.Filei

java 计算文件目录下文件总大小的几种多线程并发实现

1.单线程实现

package com.mime;import java.io.File;import java.util.ArrayList;import java.util.List;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.ForkJoinTask;import java.util.concurrent.RecursiveTask;public class FileSize {private final static ForkJoinPool forkJoinPool = new ForkJoinPool();private static class FileSizeFinder extends RecursiveTask<Long> {final File file;public FileSizeFinder(final File theFile) {file = theFile;}@Overridepublic Long compute() {long size = 0;if (file.isFile()) {size = file.length();} else {final File[] children = file.listFiles();if (children != null) {List<ForkJoinTask<Long>> tasks = new ArrayList<ForkJoinTask<Long>>();for (final File child : children) {if (child.isFile()) {size += child.length();} else {tasks.add(new FileSizeFinder(child));}}for (final ForkJoinTask<Long> task : invokeAll(tasks)) {size += task.join();}}}return size;}}public static void main(final String[] args) {final long start = System.nanoTime();final long total = forkJoinPool.invoke(new FileSizeFinder(new File("/home")));final long end = System.nanoTime();System.out.println("Total Size: " + total);System.out.println("Time taken: " + (end - start) / 1.0e9);}}


热点排行