我正在用java编写一个应用程序,允许我运行其他应用程序。为此,我使用了一个Process类对象,但是当我这样做时,应用程序在退出之前等待进程结束。有没有办法在Java中运行外部应用程序,但是不要等到它完成?
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();
}
答案 0 :(得分:3)
ProcessBuilder.start()不会等待进程完成。您需要调用Process.waitFor()来获取该行为。
我用这个程序做了一个小测试
public static void main(String[] args) throws IOException, InterruptedException {
new ProcessBuilder("notepad").start();
}
在netbeans中运行时,它似乎仍在运行。当使用java -jar从命令行运行时,它会立即返回。
所以你的程序可能还没有等待退出,但你的IDE看起来似乎是这样。
答案 1 :(得分:0)
您可以在另一个主题中运行它。
public static void main(String[] args) {
FastAppManager appManager = new FastAppManager();
appManager.startFastApp("notepad");
}
public void startFastApp(final String name) throws IOException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(new Runnable() {
@Override
public void run() {
try {
Process process = new ProcessBuilder(name).start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
您可能希望根据需要启动守护程序线程:
ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread();
thread.setDaemon(true);
return thread;
}
});