Java线程问题

标签 java multithreading

我正在尝试实现一个使用线程在服务器上执行并发命令的场景。这些命令只是将请求发送到服务器上运行的服务,并作为返回获得所需的输出。

这些命令是根据读取文件生成的,用户将其路径作为应用程序的输入。 根据上述文件中的每一行,将生成一个命令并在服务器上运行。 我通过调用 Linux 机器上的 bash 进程实例来运行这些命令。 上述的一个简短的伪实现如下。

Class A {
public static void main(blah blah)
//take all user inputs, one of which is the location of the file that is to be read.
try {
            Runnable runnable =new bckwork(//pass the inputs taken from the user//);
            thread = new Thread(runnable);
            thread.start();
        }
        catch (Exception e) {
           e.printStackTrace();
        }
}

以及执行实际工作的类 --

public class bckwork implements Runnable {

bckwork(//takes in all input that the other class passes on) {
        //assigns to local variables
    }
public void run() {
        // TODO Auto-generated method stub
    try{
        Process proc = null;
        proc = Runtime.getRuntime().exec("/bin/bash", null, dir);
         if (proc != null) {
          String cmd="";
          BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));

          PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);

           BufferedReader br = new BufferedReader(blah blah blah);//reads every line in the file that was passed onto this class.
              String strLine;
          while ((strLine = br.readLine()) != null)   {
                 cmd=blah+blah+blah//the command is generated,whatever is read off the file is a part of the command.
                 out.println(cmd);
             String line;
              while ((line = in.readLine()).length()>1) {
                    line = in.readLine();
                    System.out.println(line);
                    proc.waitFor();
                    in.close();
                    out.close();
                    proc.destroy();
                      }
        }
}
}catch(Exception e){}
}
}

上述代码片段的问题在于,它们仅针对正在读取的文件中的第一行运行,然后执行会陷入某种死锁。我猜测文件中的下一行永远不会被读取。我的意图是为正在读取的每一行或基本上正在构造的每个命令启动一个线程。

任何有关如何纠正此错误的指示将不胜感激。

最佳答案

while ((line = in.readLine()).length()>1) 

in.readLine 等待输入并卡住整个应用程序。

关于Java线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3329682/

相关文章:

java - 让 java 和 flash 相互交谈

c# - C#中的IPv6隧道多线程

multithreading - 加入第一个完成的线程?

java - 如何使用现有基类对象构造派生类

java - 并发多线程批量向Mysql插入/更新数据

java - 使用 JasperReports 创建具有样式的 Excel

java - 使用 ANTLR 的嵌套 boolean 表达式解析器

java - 将 JButton 放在右下角

C#在不按住按钮的情况下单击按钮运行耗时的方法

java - 表渲染器在 Java 中无法正常工作