[英]Why Java parallel file writing is not working?
我正在嘗試編寫一個腳本,該腳本將使用不同的參數運行 a.exe 程序 4 次。 我為每個.exe 運行創建了一個線程。 每個線程都會寫一個 output 文件。 我的問題是,它應該並行寫入,但正如您在下面的屏幕截圖中看到的那樣,文件一個接一個地寫入。 這應該如何解決?
下面是主要方法:
public static void main (String args[]) {
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.execute(new RunnableReader("myprogram.exe", param1, outputFile1));
executor.execute(new RunnableReader("myprogram.exe", param2, outputFile2));
executor.execute(new RunnableReader("myprogram.exe", param3, outputFile3));
executor.execute(new RunnableReader("myprogram.exe", param4, outputFile4));
executor.shutdown();
}
這是可運行的 class:
public class RunnableReader implements Runnable {
private String program;
private String param;
String outputFile;
public RunnableReader(String program, String param, String outputFile) {
this.program = program;
this.param = param;
this.outputFile = outputFile;
}
@Override
public void run() {
try {
ProcessBuilder pb = new ProcessBuilder(program, param);
pb.redirectOutput(ProcessBuilder.Redirect.PIPE);
pb.redirectErrorStream(true);
Process proc = pb.start();
InputStream stream = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, true));
for(String output; (output = reader.readLine()) != null) {
writer.append(output);
writer.append("\n");
}
writer.close();
reader.close();
stream.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
我自己無法對此進行測試,也不知道它是否真的會導致執行阻塞。 但是對於它的價值,我認為我應該指出您可能不需要閱讀流程的InputStream
。
正如Oracle 文檔所述, ProcessBuilder.redirectOutput(ProcessBuilder.Redirect.PIPE)
導致Process.getInputStream()
返回進程的標准 output。
考慮到這一點,您可以擺脫整個for-loop
,而只需執行類似ProcessBuilder.redirectOutput(new File(outputFile))
的操作,以便您的方法看起來像這樣
@Override
public void run() {
try {
ProcessBuilder pb = new ProcessBuilder(program, param);
pb.redirectOutput(new File(outputFile));
pb.redirectErrorStream(true);
Process proc = pb.start();
} catch(IOException e) {
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.