Java线程没有清理
我目前正在尝试编写一个记录器风格的线程。我没有使用现有的 API,因为这部分是为了改进我的线程处理。
当线程中断时,我需要它正常关闭,刷新最后一条排队消息并关闭文件流。
目前,它已关闭,但消息通常仍在队列中,我担心文件流没有正常关闭。
这是我的跑步()
while(!shutdown){
writeMessages();
try{
Thread.sleep(5000);
}
catch (InterruptedException e) {
}
}try {
writeMessages();
} catch (CustomException e1) {
e1.printStackTrace();
}
try {
logFile.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
errFile.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm currently attempting to write a Logger style thread. I'm not using the existing API because this is partially an exercise to improve my threading.
When the thread is interrupted, I need it to shutdown gracefully, flushing the last of it's queued messages and closing the file streams.
Currently, it shuts down but messages are often still in queue, and I'm concerned that the file streams aren't being closed gracefully.
This is my run()
while(!shutdown){
writeMessages();
try{
Thread.sleep(5000);
}
catch (InterruptedException e) {
}
}try {
writeMessages();
} catch (CustomException e1) {
e1.printStackTrace();
}
try {
logFile.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
errFile.close();
} catch (IOException e) {
e.printStackTrace();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java 有非常巧妙的方法来关闭线程。它称为中断标志。当你想中断线程时,你只需编写以下代码:
在后台线程的 Runnable 中,你应该检查中断标志并采取相应的行为。如果您希望线程在留下消息之前一直存在,您可以按照以下方式执行此操作(我假设您有某种方法检查是否有任何消息留下。在我的情况下,它是
BlockingQueue
):还有一件事。您应该确保在请求线程关闭后消息不会添加到队列中,或者在写入线程之前关闭所有生成消息的线程。这也可以通过检查线程中断标志来完成(您需要知道对编写器线程的引用):
我还建议您查看
java.util.concurrent
包。它有很多用于多线程应用程序的有用工具。Java has very neat way to shutdown threads. It's called interruption flag. When you want to interrupt thread you simply write following code:
And in the
Runnable
of background thread you should check interruption flag and behave accordingly. If you want thread to survive until messages are left you can do it in a following manner (I assume you have some way of checking is there any messages left. In my case it's aBlockingQueue
):One more thing. You should ensure that messages are not added to the queue after thread shutdown is requested or shutdown all threads generating messages before writing thread. This also could be done checking thread interruption flag (you need to know reference to a writer thread):
Also I recommends you to see at
java.util.concurrent
package. It have a lot of useful tools for multithreaded applications.使用 finally 块添加刷新指令。
Use the finally block to add your flushing instructions.
所有其他评论都很好,我只是想添加 - 确保在关闭输出流之前在输出流上调用了flush()。
All other comments are good, I just want to add - make sure that you called flush() on your output streams before closing them.