package fileLock; import java.io.File; import java.io.RandomAccessFile; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; /** * @ClassName: FileLock * @Description: TODO * @author Zhou Shengshuai * @date 2014年9月22日 下午2:03:04 * */ public class FileLock { private ExecutorService threadPool = null; private Collection<File> files = null; public void initial() { threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); files = FileUtils.listFiles(new File("lock"), new String[] { "lck", "LCK" }, false); } public void execute() { Iterator<File> iterator = files.iterator(); while (iterator.hasNext()) { File file = iterator.next(); ThreadTask threadTask = new ThreadTask(file); threadPool.submit(threadTask); } } public void destroy() { threadPool.shutdown(); while (!threadPool.isTerminated()) ; } public static void main(String[] args) { FileLock fileLock = new FileLock(); fileLock.initial(); fileLock.execute(); fileLock.destroy(); } } class ThreadTask implements Callable<File> { private File file = null; public ThreadTask(File file) { this.file = file; } @Override public File call() throws Exception { if (file == null || !file.isFile()) { throw new Exception("File is null or non-file"); } RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rws"); java.nio.channels.FileLock fileLock = null; while (true) { fileLock = randomAccessFile.getChannel().tryLock(); if (fileLock != null) { break; } } randomAccessFile.writeBytes("123\n"); if (fileLock != null) { fileLock.release(); } IOUtils.closeQuietly(randomAccessFile); return file; } }