用Java中的多个线程写入FileOutputStream [英] Write to FileOutputStream from multiple threads in Java

查看:2494
本文介绍了用Java中的多个线程写入FileOutputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java FileOutputStream 对象上调用 write 是否可以安全地形成多个线程?请问输出是正确的序列化的?

澄清:

在我的情况下,类记录器包含一个FileOutputStream引用,多线程可以调用记录器写入,格式化输出并调用FileOutputStream写入。

我应该同步我的记录器写入方法,以保证来自多个线程的消息不混合?

解决方案

一个文件不能在 write-mode ,所以答案是否定的。看到你的编辑后,是的,你应该引入同步到你的记录器,以确保一次只有一个线程访问流。只是一个建议,你为什么不去 Log4J ?它已经处理你的使用情况。


Is it safe to call write on Java FileOutputStream object form multiple threads? Will the output be serialized correctly?

clarification:

In my case the class logger holds a FileOutputStream reference, and multiple threads can call logger write, that formats the output and calls FileOutputStream write.

Should I synchronize my logger write method to warrant that the messages from multiple threads are not mixed?

解决方案

A file can not be opened more than once in write-mode, so the answer is no.

After seeing your edit, yes you should introduce synchronization into your logger to make sure the stream is accessed only by one thread at a time. Just a suggestion, why don't you go for Log4J? It already handles your use case.

这篇关于用Java中的多个线程写入FileOutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆