Java利用文件锁实现进程互斥

备忘

  @SuppressWarnings("ResultOfMethodCallIgnored")
  public static void main(String[] args) {
    FileLock lock;
    Paths.get(LOCK_PATH).toFile().mkdir();
    try (FileOutputStream fileOutputStream = new FileOutputStream(Paths.get(LOCK_PATH,"lockfile" ).toString(), true)) {
      FileChannel channel = fileOutputStream.getChannel();
      lock = channel.tryLock();
      if (lock == null || !lock.isValid()) {
        log.info("正在等待其他进程退出...");
        lock = channel.lock();
      }
      try {
        execute(args);
      } finally {
        lock.release();
      }
    } catch (Exception e) {
      log.error("Fatal Error", e);
    }
  }

 

posted @ 2025-07-01 02:44  Jackie_JK  阅读(11)  评论(0)    收藏  举报