gpt4 book ai didi

java 8 lambda递归失败

转载 作者:行者123 更新时间:2023-12-02 12:23:39 30 4
gpt4 key购买 nike

我正在尝试使用 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());
}

}

}

最佳答案

问题是你的程序没有等待这些子任务被执行。它立即返回。因此仅打印出第一级目录,因为这些 println 不依赖于任何此类可运行的子目录来执行。

通常可以调用ExecutorServiceshutdownawaitTermination来等待任何挂起的任务运行。但是,这在您的情况下不起作用,因为更深层次的目录级别的相应任务直到稍后执行其父目录的任务时才会添加。

关于java 8 lambda递归失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45595448/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com