简单的FileLock实例

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileLockDemo {

	/**
	 * Filelock 防止程序在运行期间,线程在访问文件的过程中修改文件导致Buffer中
	 * 的部分或者全部内容不可读,造成程序异常。
	 * 例子中展示的是新开以个线程访问主线程Filelock的文件。
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		File file = new File("D://in.txt");
		FileOutputStream fis = new FileOutputStream(file);
		FileChannel fc = fis.getChannel();
		FileLock flock = fc.tryLock();
		if(flock.isValid()){
			System.out.println(file.getName()+ "is locked");
		}
		new Thread(){
			public void run(){
				try{
					File file = new File("D://in.txt");
					FileOutputStream fi = new FileOutputStream(file);
					fi.write('b');
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}.run();
		flock.release();
		System.out.println(file.getName()+ "is released");
		fc.close();
		fis.close();
	}

}

 结果是该文件无法被新起的线程访问,运行结果:
in.txtis locked
java.io.IOException: The process cannot access the file because another process has locked a portion of the file
at java.io.FileOutputStream.write(Native Method)
at com.cn.tibco.nio.FileLockDemo$1.run(FileLockDemo.java:32)
at com.cn.tibco.nio.FileLockDemo.main(FileLockDemo.java:37)
in.txtis released

你可能感兴趣的:(java,thread)