2012-03-08 109 views
1

我正在用java寫一個應用程序,允許我運行其他應用程序。爲此,我使用了一個Process類對象,但是當我這樣做時,應用程序會在退出之前等待該過程結束。有沒有辦法在Java中運行外部應用程序,但不要等待它完成?在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

您可以在另一個線程中運行它。

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

我想他想讓他的lancher在啓動程序後終止。 – 2016-01-10 06:48:55

2

ProcessBuilder.start()不等待進程結束。您需要調用Process.waitFor()來獲取該行爲。

我做了一個小測試這個程序

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

當在NetBeans中運行它似乎仍在運行。當從命令行運行java -jar時,它立即返回。

因此,您的程序可能不會等待退出,但您的IDE使它看起來如此。

+0

ProcessBuilder在循環內部運行時的情況如何。它是否等待完成進入下一個循環? – sijo0703 2016-02-26 01:37:46

+0

如果您使用waitFor()它會。 – 2016-02-26 06:29:32