【发布时间】:2014-01-30 21:53:13
【问题描述】:
这是我所拥有的: 我有一个启动进程的线程,该进程由 ProcessBuilder 创建并在终端中启动字符串命令。有许多并发线程执行相同的操作,但处理不同的数据。
这是我想做的: 我想让一个线程(它启动一个进程)等待该进程直到它完成。我想出了两种方法,都没有奏效。
方法一:使用 process.waitFor();这会导致所有并发线程等待一个进程(通常是第一个进程)完成。 waitFor() 的描述;说它使单个线程等待,但这不是它所做的,它实际上使所有线程等待。因此程序不再是并发的。
方法 2:运行另一个线程,从该进程中读取管道流,等待直到有流,然后运行应该在该进程之后运行的函数。缺点是现在线程很多,所以我不喜欢使用这种方法。这种方法的另一个问题是,我对应该使用进程的哪些属性感到困惑? OutputStream、InputStream 还是 ErrorStream?
代码如下:
public class Thread1 extends Thread{
private String[] incommand; //this is the command for the process builder
private String newoutputfile;
InputStream ins = null;
Reader r = null;
BufferedReader br = null;
ProcessBuilder pbtx = null;
public Thread1(String[] incommand, String newoutputfile){
super("Thread1");
this.incommand = incommand;
this.newoutputfile = newoutputfile;
this.pbtx = new ProcessBuilder();
}
@Override
public void run(){
try{
pbtx.command(incommand);
Process ptx = pbtx.start();
//to make sure job is done
ptx.waitFor(); //problem is apparently here
// made sure job is done
//the next function is supposed to run after the process is finished
rite();
//
} catch (IOException ex){
System.out.println("exception in thread t1");
ex.printStackTrace();
}
catch (InterruptedException yo){
System.out.println("exception in thread t1");
}
}
顺便说一句,该进程是一个 ffmpeg 进程,每个进程都处理不同的视频数据(没有数据依赖关系或竞争条件或这里曾经有过的东西)。所有这些thread1线程都是由另一个函数(main)中的另一个主线程创建和启动的。 Linux中的操作系统。 IDE 是 Netbeans(我从那里得到每个函数的描述)。我试图使复制粘贴的代码尽可能短(为了简单起见),所以如果您认为需要其他功能或程序其余部分的代码,请通知我将它们粘贴在这里。
非常感谢,
【问题讨论】:
-
你是如何开始你的话题的?我严重怀疑 Process.waitFor() 会冻结所有线程。
-
谢谢你的回答。线程由主程序中的 threadobject.start() 和 threadobject.join() 启动。不使用 .join() 会导致线程争用它们的输入变量。
-
好吧,使用
.join()会导致线程等待。Process.waitFor()与此无关。
标签: java multithreading process wait