Java 如何在使用线程时安全地关闭流
我有以下代码的线程:Java 如何在使用线程时安全地关闭流,java,stream,Java,Stream,我有以下代码的线程: public void run() { try { fileProcessor = new FileProcessor(); fileProcessor.process(); } catch (RuntimeException e) { // ... } finally { if (fileProcessor != null) { fileProcessor.close(); } } } 方法filePro
public void run() {
try {
fileProcessor = new FileProcessor();
fileProcessor.process();
} catch (RuntimeException e) {
// ...
} finally {
if (fileProcessor != null) {
fileProcessor.close();
}
}
}
方法fileProcessor.process()代码>也运行一些新线程:
protected void process() {
this.writer = new Writer();
final MyClient client = new MyClient();
client.start();
}
此代码有时引发异常
Caused by: java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:26)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:99)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:116)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:203)
at java.io.Writer.write(Writer.java:140)
at java.io.Writer.append(Writer.java:210)
我怎样才能安全地关闭这条河?因为使用fileProcessor.close()
现在可能我关闭了这个流,但是仍然有一些线程在使用它。不要在process()
方法中启动新线程,而是同步运行该功能
或者从process()
方法中调用close()
方法。不要在process()
方法中启动新线程,而是同步运行该功能
或者从process()
方法中调用close()
方法。对fileProcessor中的所有线程使用thread.join()
。因此,它将等待所有线程完成其任务
client.start();
client.join(); // this will make sure client thread finished before proceed to next step
对fileProcessor中的所有线程使用thread.join()
。因此,它将等待所有线程完成其任务
client.start();
client.join(); // this will make sure client thread finished before proceed to next step
这里有些困惑。。这将关闭相应的线程文件处理器。您可以发布更多使用此方法的代码或此run
method.updated的内部代码吗。我只想在fileProcessor中的所有线程完成后关闭流。我不知道这能帮我吗?synchronized(this){fileProcessor.close();}Thread.join()
似乎是这里的答案。。。如不变量所述。那么这不能用synchronized完成?这里有点混乱。。这将关闭相应的线程文件处理器。您可以发布更多使用此方法的代码或此run
method.updated的内部代码吗。我只想在fileProcessor中的所有线程完成后关闭流。我不知道这能帮我吗?synchronized(this){fileProcessor.close();}Thread.join()
似乎是这里的答案。。。如不变量所述。那么这不能用synchronized完成吗?