添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

在后台运行JAVA中的BASH命令

1 人关注

我做了一个执行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();
    
java
linux
multithreading
bash
jakarta-ee
Damian
Damian
发布于 2013-12-24
1 个回答
Elliott Frisch
Elliott Frisch
发布于 2013-12-24
已采纳
0 人赞同

你不需要那个内层类(你也不想 waitFor )......只要使用

for(String element : arrayExplodedCommands)
    listCommands.add(element);
ProcessBuilder ps = new ProcessBuilder(listCommands);
ps.redirectErrorStream(true);
Process p = ps.start();
// That's it.