public
class FileLockTest {
public static void main(String[] args) throws Exception{
lock(); //文件锁-独占锁
lock(); //再次
获取文件锁为空
}
static void lock()throws Exception{
File file = new File("D:\\lock");
RandomAccessFile lockFile = new RandomAccessFile(file, "rw");
FileLock lock = lockFile.getChannel().tryLock(0, 1, false);
if (lock == null || lock.isShared() || !lock.isValid()) {
throw new RuntimeException("Lock
failed");
}
lockFile.getChannel().write(ByteBuffer.wrap("lock3".getBytes()));
lockFile.getChannel().force(true);
/*if (lockFile != null && lock != null) {
try {
lock.release();
lockFile.close();
} catch (IOException e) {
}
}*/
}
}