在文件上创建共享文件锁
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 */