最近在学习Java8中的CompletableFuture类。想要学习一下多线程类,自己也就尝试写了些代码。
不足之处还请有识之士多多指点!
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Test {
private static final ExecutorService serivce = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public Test() {
// TODO Auto-generated constructor stub
}
private static List<Path> execFileCopy(String src, String tar) {
List<Path> lst = Collections.synchronizedList(new ArrayList<Path>());
try {
Path target = FileSystems.getDefault().getPath(tar);
Files.walkFileTree(Paths.get(src), new SimpleFileVisitor<Path>() {
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Objects.requireNonNull(dir);
Objects.requireNonNull(attrs);
Path targetPath = target.resolve(dir.subpath(0, dir.getNameCount()));
Files.createDirectories(targetPath);
return FileVisitResult.CONTINUE;
}
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Objects.requireNonNull(file);
Path targetPath = target.resolve(file.subpath(0, file.getNameCount()));
CompletableFuture.runAsync(() -> {
try {
Files.copy(file, targetPath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}, serivce);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
return lst;
}
public static void main(String[] args) throws Exception {
long s = System.currentTimeMillis();
String tar = "E:\\2";
String src = "F:\\angular2"; // 共734M大小目录 内含386M文件(1)、185M文件(1)、其余26,918个文件均为K级碎片文件
execFileCopy(src, tar);
serivce.shutdown();
while (!serivce.isTerminated()) {
serivce.awaitTermination(1, TimeUnit.SECONDS);
}
System.out.println((System.currentTimeMillis() - s) / 1000); // 耗时26秒 系统环境(i5-3337U 4G内存 256GSSD硬盘 Win10)
}
}