日期:2014-05-20 浏览次数:20980 次
public class TestFileLock {
public static void main(String[] args) throws Exception{
Runnable r = new Runnable(){
public void run()
{
try{
RandomAccessFile raf = new RandomAccessFile ("c:\\test.txt","rw");
FileChannel fc = raf.getChannel();
FileLock lock = fc.tryLock();
if(lock!=null)
{
System.out.println(Thread.currentThread().getName()+": Open the File");
Thread.sleep(100000);
lock.release();
System.out.println(Thread.currentThread().getName()+": Releae the File.");
}
else
System.out.println(Thread.currentThread().getName()+": Because the file is being used, you can't get the file lock.");
}catch(Exception e)
{
}
}
};
new Thread(r).start();
new Thread(r).start();
}
}