我创建了一个执行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 :(得分: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>();