我尝试使用以下代码锁定文件并向其写入:
public class TrainSetBuildTask implements Runnable {
private String pathname;
public TrainSetBuildTask(String pathname){
this.pathname = pathname;
}
@Override
public void run() {
try {
String content = "content\n";
//write to a file
FileOutputStream os = new FileOutputStream(new File(pathname), true);
FileChannel channel = os.getChannel();
FileLock lock = channel.tryLock();
if (lock != null) {
ByteBuffer bytes = ByteBuffer.wrap(content.getBytes());
channel.write(bytes);
lock.release();
}
channel.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
同时创建两个类实例的新线程:
String pathname = "/home/sjtu123/test.arff";
TrainSetBuildTask task1 = new TrainSetBuildTask(pathname);
Thread t1 = new Thread(task1);
TrainSetBuildTask task2 = new TrainSetBuildTask(pathname);
Thread t2 = new Thread(task2);
t1.start();
t2.start();
我遇到了OverlappingFileLockException错误。我想知道为什么会出现这种情况,因为我只在每个线程中锁定文件一次?如何修复我的代码?
FileLock
的用途是什么呢?既然它不能用于协调想要写入文件的线程。@Attila - jerry_sjtu