62,615
社区成员
发帖
与我相关
我的任务
分享
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileLockTest {
public static void main(String[] args) throws Exception {
Thread t =new Thread(){
@Override
public void run() {
FileChannel channel;
try {
channel = new RandomAccessFile(new File("c:/menu.txt"), "rw").getChannel();
FileLock lock =channel.lock();
System.out.println("Thread1 拿到lock:"+lock+" "+lock.isShared());
channel.position(channel.size());
Thread.sleep(1000*10);
for(int i =0;i<10;i++){
channel.write(ByteBuffer.wrap((i+" hello \n").getBytes()));
}
lock.release();
channel.close();
System.out.println("over1");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
Thread.sleep(500);
t =new Thread(){
@Override
public void run() {
System.out.println("Thread2 开始");
FileChannel channel;
try {
channel = new RandomAccessFile(new File("c:/menu.txt"), "rw").getChannel();
ByteBuffer bb=ByteBuffer.allocate(1024);
channel.read(bb);
bb.flip();
System.out.println(bb.asCharBuffer());
System.out.println("over2");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
}