Java语言锁

示例

可以使用FileChannel可以从Input Outputstreams和readers

例子 streams

//打开文件流FileInputStream ios = new FileInputStream(filename);

    // 获取基础渠道
    FileChannel channel = ios.getChannel();

    /*
    *尝试锁定文件。true表示锁是否共享,即多个进程可以获取一个锁
    *使用false和readable channel only的共享锁(只读)将生成异常。你应该
    *使用false时,请使用可写通道(取自FileOutputStream)。特洛克总是会马上回来
     */
    FileLock lock = channel.tryLock(0, Long.MAX_VALUE, true);

    if (lock == null) {
        System.out.println("Unable to acquire lock");
    } else {
        System.out.println("Lock acquired successfully");
    }

    // 您还可以使用阻止调用,该调用将一直阻止直到获得锁为止。
    channel.lock();

    //一旦完成所需的文件操作。释放锁
    if (lock != null) {
        lock.release();
    }

    // 之后关闭文件流
    // 读者范例
    RandomAccessFile randomAccessFile = new RandomAccessFile(filename,  "rw");
    FileChannel channel = randomAccessFile.getChannel();
    //重复与上述相同的步骤,但是现在您可以在通道处于读写模式时将shared用作true或false