3

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

2 回答 2

3

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

我用这个程序做了一个小测试

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

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

所以你的程序可能没有等待退出,但你的 IDE 让它看起来如此。

于 2012-03-08T20:42:06.290 回答
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;
        }
    });
于 2012-03-08T20:30:40.120 回答