gpt4 book ai didi

java - 多线程访问文件

转载 作者:搜寻专家 更新时间:2023-10-30 21:26:21 26 4
gpt4 key购买 nike

我们有一个多线程 java 程序。多线程将写入一个文件,一个线程将从该文件读取。我正在寻找一些设计理念。是否需要同步?

最佳答案

FileChannel理论上是线程安全的。来自 javadoc:

File channels are safe for use by multiple concurrent threads. The close method may be invoked at any time, as specified by the Channel interface. Only one operation that involves the channel's position or can change its file's size may be in progress at any given time; attempts to initiate a second such operation while the first is still in progress will block until the first operation completes. Other operations, in particular those that take an explicit position, may proceed concurrently; whether they in fact do so is dependent upon the underlying implementation and is therefore unspecified.

如果您可以使用这些,那么您就可以使用内置同步,而不必自己编写。

关于java - 多线程访问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/302769/

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