gpt4 book ai didi

Java process.waitFor() 不会阻塞线程

转载 作者:行者123 更新时间:2023-12-01 18:18:09 26 4
gpt4 key购买 nike

我正在构建一个应用程序,该应用程序应该在我的 Windows PC 上启动其他应用程序。当应用程序启动时,我的代码应该等到我关闭该程序才能继续执行。

System.out.println("Starting ccleaner...");
Process p = Runtime.getRuntime().exec("C:\\Program Files\\CCleaner\\CCleaner64.exe");
System.out.println("Before wait");
p.waitFor();
//Here it should wait until the subprocess is
// exited/the ccleaner programs exit button is clicked
System.out.println("After wait");

所发生的只是它不会等待,而是立即执行。我在文档中查找了 waitFor() 方法,它说:

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

这对我来说似乎很清楚。不过,我在本网站上查看了有关此问题的其他问题,并找到了一些涉及读取流的解决方案,但据我了解,这些解决方案主要是当您拥有自己想要运行的bat文件时。但我也尝试过这些,但没有让它发挥作用。有趣的是,我上面的代码或多或少与tutorialpoints.com 上提供的代码相同。

我也尝试过使用 process.isAlive() 但我似乎也无法让其工作。

有人知道我在这里做错了什么吗?

最佳答案

waitFor() 完全符合您的预期。你的理解没有错。

我怀疑您正在运行的程序确实立即退出,导致 waitFor() 立即返回。当父进程退出时,它可能会启动一个或多个正在执行实际工作的子进程。

关于Java process.waitFor() 不会阻塞线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38464454/

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