gpt4 book ai didi

java - ExecutorService 和写入文件

转载 作者:行者123 更新时间:2023-12-02 09:40:04 30 4
gpt4 key购买 nike

我正在尝试使用ExecutorService为了写入文件。但是,当我执行此代码时,执行到 outFile.close();在执行完成之前,会抛出

java.io.IOException: Stream closed

如何调用outFile.close()只有在所有任务完成之后?

(PS:为了代码清晰起见,我删除了所有 try/catch block 。)

ExecutorService executor = Executors.newFixedThreadPool(3);

for (int i = 1; i <= 1000; i++) {
final int counter = i;
executor.execute(new Runnable() {
@Override
public void run() {
outFile.write(wld.getWord(counter) + "successful");
outFile.write("\n");
}
});
}

outFile.close();

最佳答案

您应该首先等待所有任务完成。提交所有作业后,您可以调用 executor.shutdown() 并使用 executor.awaitTermination() 等待所有线程完成。

这是一个例子:

ExecutorService executor = Executors.newFixedThreadPool(3);

for (int i = 1; i <= 1000; i++) {
final int counter = i;
executor.execute(new Runnable() {
@Override
public void run() {
outFile.write(wld.getWord(counter) + "successful");
outFile.write("\n");
}
});
}

executor.shutdown(); //shut down executor
executor.awaitTermination(60, TimeUnit.SECONDS); //waiting for 60 seconds

outFile.close(); //and then you may safely close the stream knowing that all the tasks have finished

注意:由于超时,主线程可能会在所有作业完成之前被唤醒。您可以增加该时间或循环等待,直到满足 isTermminate() 条件:

executor.shutdown();
while (!executor.isTerminated()) {
executor.awaitTermination(1, TimeUnit.SECONDS);
}

关于java - ExecutorService 和写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57151707/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com