2013-12-23 45 views
1

我做了一個執行BASH命令的函數,我想讓它在後臺運行並且永不停止主程序的執行。在後臺運行JAVA中的BASH命令

我可以使用screen -AmdS screen_thread123 php script.php但主要的想法是,我瞭解並理解線程是如何工作的。

我對此有一個基本的認識,但現在我想建立一個快速的動態線程像波紋管的例子:

public static void exec_command_background(String command) throws IOException, InterruptedException 
{ 

    List<String> listCommands = new ArrayList<String>(); 
    String[] arrayExplodedCommands = command.split(" "); 

    // it should work also with listCommands.addAll(Arrays.asList(arrayExplodedCommands)); 
    for(String element : arrayExplodedCommands) 
    { 
     listCommands.add(element); 
    } 

    new Thread(new Runnable(){ 
     public void run() 
     { 
      try 
      { 
       ProcessBuilder ps = new ProcessBuilder(listCommands); 

       ps.redirectErrorStream(true); 
       Process p = ps.start(); 

       p.waitFor(); 
      } 
      catch (IOException e) 
      { 
      } 
      finally 
      { 
      } 
     } 
    }).start(); 
} 

,這讓我這個錯誤

NologinScanner.java:206: error: local variable listCommands is accessed from within inner class; needs to be declared final 
ProcessBuilder ps = new ProcessBuilder(listCommands); 
1 error  

爲什麼是的,我該如何解決它?我的意思是我如何從這個塊訪問變量listCommands

new Thread(new Runnable(){ 
     public void run() 
     { 
      try 
      { 
       // code here 
      } 
      catch (IOException e) 
      { 
      } 
      finally 
      { 
      } 
     } 
    }).start(); 
} 

謝謝。

回答

0

你並不需要一個內部類(和你不想waitFor)...只是使用

for(String element : arrayExplodedCommands) 
{ 
    listCommands.add(element); 
} 
ProcessBuilder ps = new ProcessBuilder(listCommands); 

ps.redirectErrorStream(true); 
Process p = ps.start(); 
// That's it. 

至於你訪問你的原塊中的變量listCommands的問題;使參考最終 - 像這樣

final List<String> listCommands = new ArrayList<String>(); 
+0

是的,你是對的,你不必等待,但我們可以說,我想使用線程,代碼將如何看起來像? – Damian

+0

@Damian ProcessBuilder已經爲您運行在一個單獨的線程中。請注意,你可以調用'start()'。 –

+0

我測試了兩個。工作很有意思。非常感謝你。我之前沒有使用過最終決賽。我對決賽的瞭解是你不能再改變它了。 – Damian