我有几个线程(其中一些是由Process X产生的,另一个由Process Y等等),每个线程都需要写入一个文件MyFile.但是,如果线程T1首先开始写入MyFile,那么当Thread T2开始写入时,需要等待T1释放该文件,以便读取在线程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
}
}
我的问题是:如何在上述代码中完成locked_section?我正在研究FileLock类,但是它在Javadoc中说:“文件锁代表整个Java虚拟机,它们不适用于通过同一虚拟机中的多个线程控制对文件的访问.