gpt4 book ai didi

java - Java中PrintStream的线程安全

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:16 25 4
gpt4 key购买 nike

我正在尝试写入一个文件。我需要能够“附加”到文件而不是覆盖它。另外,我需要它是线程安全和高效的。我目前的代码是:

private void writeToFile(String data) {
File file = new File("/file.out");
try {
if (!file.exists()) {
//if file doesnt exist, create it
file.createNewFile();
}
PrintStream out = new PrintStream(new FileOutputStream(file, true));
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
out.println(dateFormat.format(date) + " " + data);

out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

一切都很好。我只是不知道 PrintStream 是否是线程安全的。所以,我的问题是:从多个 PrintStream 实例写入同一个物理文件安全吗?如果是这样,它是使用锁定(降低性能)还是排队?您知道任何线程安全且使用队列的 native Java 库吗?如果没有,我自己写也没问题。在我编写自己的代码之前,我只是想看看是否有本地的东西。

最佳答案

PrintStream 源表明它是线程安全的。

如果你想从不同的线程写入同一个文件,为什么不跨线程共享同一个 PrintStream 实例呢? PrintStream 为您进行同步。

/**
* Prints a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>String</code> to be printed.
*/
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}

关于java - Java中PrintStream的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632585/

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