我有几个线程(其中一些由Process X生成,其他由Process Y生成,等等),每个线程都需要写入一个文件MyFile.但是,如果Thread T1开始写MyFile第一,那么,当Thread T2开始写,需要等待T1到释放文件,以便它可以读取写在该内容Thread T1.换句话说,每个线程都有一个finalizeThread方法,如下所示:
private void finalizeThread() {
File f = new File("MyFile.dat");
f.createNewFile(); // atomically creates the file, if it doesn't exist
locked_section {
readContentsFromFile(f); // read contents if some other thread already modified the file
modifyContentsFromFile(f); // modify
writeFile(f); // write, so that new threads can see the content modified by this thread
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何locked_section在上面的代码中完成?我正在研究这个FileLock类,但它在Javadoc中说"文件锁代表整个Java虚拟机.它们不适合控制同一个虚拟机中多个线程对文件的访问." .
And*_*Dog 12
如果只从程序访问该文件,则同步锁定对象是可以的.但是,如果您希望在处理文件时保护文件不被其他程序更改,则可以在java.nio.channels.FileLock(示例)中使用Java的文件锁定功能.正如文中所说,请注意,在某些操作系统上,如果文件没有检查现有的文件锁,程序仍然可以更改文件.