我正在编写一个程序,该程序从同一 JVM 上的两个不同线程和不同 JVM/进程写入单个文件。有没有办法同时为线程和进程锁定文件,这样无论有多少线程/进程同时尝试写入,一次只能写入 1 个?
目前我有类似以下的东西,它适用于锁定线程,但不适用于阻塞进程。如果我尝试FileLock在下面的实现之上使用它似乎synchronized停止工作。
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import scripts.com.adz.commons.utils.FileUtilities;
import java.io.*;
public class Foo {
public static void main(String[] args) throws IOException {
Bar bar = new Bar();
bar.start();
while (true) {
FileUtilities.writeObjectToFile("C:\\test.html", "foo");
}
}
}
class Bar extends Thread {
@Override
public void run() {
while (true) {
try {
FileUtilities.writeObjectToFile("C:\\test.html", "bar");
} catch (IOException ignored) {}
}
}
}
class FileUtilitiess {
private static final Object _lock = new …Run Code Online (Sandbox Code Playgroud)