【问题标题】:Run a external application in java but don't wait for it to finish在 java 中运行一个外部应用程序,但不要等待它完成
【发布时间】:2012-03-08 20:25:20
【问题描述】:

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

【问题讨论】:

    标签: java process termination


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • ProcessBuilder 在循环中运行时怎么样。它是否等待完成进入下一个循环?
    • 如果你使用 waitFor() 它会的。
    【解决方案2】:

    你可以在另一个线程中运行它。

      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;
            }
        });
    

    【讨论】:

    • 我认为他希望他的 lancher 在启动程序后终止。
    猜你喜欢
    • 2011-12-16
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多