集册 Java实例教程 用CompletionHandler实现lock()方法

用CompletionHandler实现lock()方法

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

488
用CompletionHandler实现lock()方法

import java.io.IOException;

import java.nio.channels.AsynchronousFileChannel;

import java.nio.channels.CompletionHandler;/** 来 自 nowjava - 时代Java**/

import java.nio.channels.FileLock;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;


public class Main {

  static Thread current;


  public static void main(String[] args) {

    Path path = Paths.get("C:/folder1/", "test.txt");

    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel

        .open(path, StandardOpenOption.READ, StandardOpenOption.WRITE)) {

      current = Thread.currentThread();

      asynchronousFileChannel.lock("Lock operation status:",

          new CompletionHandler<FileLock, Object>() {

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

            public void completed(FileLock result, Object attachment) {

              System.out.println(attachment + " " + result.isValid());

              if (result.isValid()) {

                try {

                  result.release();

                } catch (IOException ex) {

                  System.err.println(ex);

                }

              }

              current.interrupt();

            }


            @Override

            public void failed(Throwable exc, Object attachment) {

              System.out.println(attachment);

              System.out.println("Error:" + exc);

              current.interrupt();

          
展开阅读全文