在Java中运行外部应用程序,但不要等待它完成 [英] Run a external application in java but don't wait for it to finish

查看:131
本文介绍了在Java中运行外部应用程序,但不要等待它完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java编写一个应用程序,允许我运行其他应用程序.为此,我使用了Process类对象,但是当我这样做时,应用程序会等待进程结束再退出自身.有没有一种方法可以用Java运行外部应用程序,但不要等待它完成?

I'm writing an app in java allowing me to run other applications. To do that, I've used an Process class object, but when I do, the app awaits the process to end before exiting itself. Is there a way to run external application in Java, but don't wait for it to finish?

public static void main(String[] args)
{
FastAppManager appManager = new FastAppManager();
appManager.startFastApp("notepad");
}

public void startFastApp(String name) throws IOException
{
    Process process = new ProcessBuilder(name).start(); 
}

推荐答案

ProcessBuilder.start()不等待进程完成.您需要调用Process.waitFor()以获取该行为.

ProcessBuilder.start() does not wait for process to finish. You need to call Process.waitFor() to get that behaviour.

我对此程序做了一个小测试

I did a small test with this program

public static void main(String[] args) throws IOException, InterruptedException {
    new ProcessBuilder("notepad").start();
}

在netbeans中运行时,它似乎仍在运行.使用java -jar从命令行运行时,它将立即返回.

When run in netbeans it appear to be still running. When running from command line with java -jar it returns immediately.

所以您的程序可能不会等待退出,但是您的IDE使其看起来像这样.

So your program is probably not waiting to exit, but your IDE makes it seem so.

这篇关于在Java中运行外部应用程序,但不要等待它完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆