我做了一个执行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()
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()
// code here
catch (IOException e)
finally
}).start();