第一个问题:
jdk文档上说FileChannel类的lock方法可以锁住文件,禁止其它进程访问,但是对于线程无效,原文如下:文件锁定以整个 Java 虚拟机来保持。但它们不适用于控制同一虚拟机内多个线程对文件的访问。但是我通过代码测试,发现不是这样的,代码如下:writeFile.java :import java.io.*;
public class writeFile extends Thread{
public void run(){
           try{
FileOutputStream out = new FileOutputStream("D:/test.txt" , true);
out.write(65);
while(true){
   Thread.sleep(2000);
   System.out.println("begin write");
   out.write(65);
   out.flush();
   System.out.println("end write");
    }
    }catch(Exception e){
e.printStackTrace();
    }
         }
}test.java :import java.io.*;import java.nio.channels.*;public class test extends Thread{

public static void main(String[] args) {
        new writeFile().start();
new test().start();
}

public void run(){
System.out.println("start");
try{
Thread.sleep(3000);
RandomAccessFile in = new RandomAccessFile("D:/test.txt" , "rw");
        FileChannel chan = in.getChannel();
                FileLock lock = chan.lock();
                in.write(56);
                System.in.read();
}catch(Exception e){
e.printStackTrace();
}
}
}运行结果就是:
begin write
end write
begin write
java.io.IOException: 另一个程序已锁定文件的一部分,进程无法访问。
at java.io.FileOutputStream.write(Native Method)
at writeFile.run(writeFile.java:32)这里发现这个问题:
多线程仍然能锁住第二个问题:
如果其它进程打开了文件,但是FileChannel仍然能够锁住它,这是怎么回事?