【发布时间】:2018-01-17 14:59:53
【问题描述】:
我正在尝试使用 lambda 递归遍历目录和每个子目录,同时将每个子目录推送到新线程。
问题是它正在通过顶级目录和 所有第一轮子目录,但拒绝深入第一级子目录中的任何子目录。
我不明白为什么它适用于第一级递归但不适用于第二级。嵌套线程和/或 lambda 函数的次数是否有限制?
下面是我的代码的相关部分:
public class Main
{
public static ExecutorService localExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public static void getFileNames(final Path dir)
{
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir))
{
for (Path path : stream) {
System.out.println(path);
if (path.toFile().isDirectory()) {
Runnable subDir = () -> getFileNames(path);
localExecutor.submit(subDir);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String... args)
{
getFileNames(
FileSystems.getDefault().getPath("C:\\A")
);
//
//I wait for it to finish all tasks in another method that contains the below
functions.localExecutor.shutdown();
try {
functions.localExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.print("Exception: the following error occured: ");
System.out.println(e.toString());
MainLogic.log.add("Exception: the following error occured: " + e.toString());
}
}
}
【问题讨论】:
-
1) 变量应该是小写的
LocalExecutor->localExecutor。 2)你不需要围绕你的 lambda 大括号。Runnable subDir = () -> getFileNames(path,i,directory);很好 3) 不要混合数组和Lists -
您是否尝试过实际调试它?像换行符,打印语句等?您的代码不完整。缺少捕获,没有返回并且没有足够的右大括号。
-
您确定等待的时间够长吗?您可能希望在列表中捕获
submit返回的Future并等待它们全部完成。或者,您可以在ExecutorService上调用shutdown以等待其完成处理。 -
@Michael - 缺少
catch是因为try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir))这是一个 try-with-resources 子句,它将自动关闭资源。 -
@OldCurmudgeon 它是 try-with-resources 但
newDirectoryStream抛出IOException这是一个需要 catch 块的检查异常(或者方法签名应该更改)。
标签: java recursion lambda subdirectory