gpt4 book ai didi

java - writer 是原子方法吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:06 27 4
gpt4 key购买 nike

我想将一些字符串写入文件。所以,我使用了 BufferedWriter 类。由于许多线程倾向于写入该文件,我想知道 writewriteLine 方法是否是原子的。

此外,我希望程序将输出写入多个文件,每个文件 100 行(比如 file.txt0、file.txt1,...)。例如

public class Main {
static ExecutorService exec = Executors.newFixedThreadPool(5);
BufferedWriter bw;
public class myWriter implements Runnable {
String str;
myWriter (String str) {
this.str = str;
}
public void run() {
bw.write(str);
bw.writeLine();
}
}
public static void main(String[] args) {
bw = new BufferedWriter(new FileWriter("train.txt"));
for (String arg: args)
exec.execute(new myWriter(arg));
exec.awaitTermination(100000, TimeUnit.MILLISECONDS);
}
}

有人可以帮助我吗?如果它们不是原子的,我怎样才能使它们成为原子的并避免碰撞?

最佳答案

不,那些不是原子的。

如果你想多次写入同一个文件,使用FileLocks .

try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();

// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}

// Release the lock
lock.release();

// Close the file
channel.close();
} catch (Exception e) {
}

关于java - writer 是原子方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9512433/

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