這裏是我有: 我有一個線程啓動一個進程,這個進程是由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