这里是我有: 我有一个线程启动一个进程,这个进程是由ProcessBuilder创建的,并在终端启动一个字符串命令。有许多并发线程执行相同的操作,但数据不同。在java中,如何让一个线程等待一个进程完成?
这是我想要做的: 我想让一个线程(启动一个进程)等待该进程,直到完成。我想出了两种方法,但都没有工作。方法1:使用process.waitFor();方法1:使用process.waitFor();方法2:使用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的过程,每个过程的工作在不同的视频数据(没有数据依赖或种族的状况或什么那么这里)。所有这些线程1线程由另一个函数(main)中的另一个主线程创建并启动。 Linux中的操作系统。 IDE是Netbeans(这是我得到每个函数的描述)。我试图尽量缩短复制粘贴的代码(为了简单起见),所以如果您认为需要其他函数或其他程序的代码,请通知我将其粘贴到此处。
非常感谢你,
你是如何开始你的线程?我严重怀疑Process.waitFor()冻结了所有的线程。 – Kayaman
谢谢你的回答。线程由threadobject.start()启动,然后在主程序中启动threadobject.join()。不使用.join()会导致线程争夺他们的输入变量。 – user2452253
那么,使用'.join()'会导致线程等待。 'Process.waitFor()'与它无关。 – Kayaman