我有这个代码的线程:
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();
现在可能我关闭了这个流,但仍然有一些线程在使用它。