【发布时间】:2012-03-28 11:03:11
【问题描述】:
我尝试锁定一个文件并使用以下代码对其进行写入:
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。我想知道为什么会发生这种情况,因为我只是在每个线程中锁定文件一次?如何修复我的代码?
【问题讨论】:
标签: java multithreading locking