2013-12-23 47 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