集册 Java实例教程 在文件上创建共享文件锁

在文件上创建共享文件锁

欢马劈雪     最近更新时间:2020-01-02 10:19:05

513
在文件上创建共享文件锁

import java.io.File;

import java.io.RandomAccessFile;
/* 
 来自 
*N o w J a v a . c o m - 时代Java*/

import java.nio.channels.FileChannel;

import java.nio.channels.FileLock;

import java.nio.channels.OverlappingFileLockException;


public class Main {

  void m() throws Exception {

    File file = new File("filename");

    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();


    FileLock lock = channel.lock(0, Long.MAX_VALUE, true);


    try {

      lock = channel.tryLock(0, Long.MAX_VALUE, true);

    } catch (OverlappingFileLockException e) {

      // File is already locked in this thread or virtual machine

    }

    /* 
    *来 自
     时 代 J a v a 公 众 号 - N o w J a v  a . c o m
    */

    
展开阅读全文