* 建立时间:2008-10-28
*/
package cn.aofeng.nio;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import cn.aofeng.util.IOUtils;
* 测试NIO中的文件锁:三个线程争抢文件锁,获得锁后向文件中写数据,然后再释放文件锁。
*
* @author aofeng <a href="mailto:aofengblog@163.com>aofengblog@163.com</a>
*/
public class FileLockThread implements Runnable {
public void run() {
Thread curr = Thread.currentThread();
System.out.println("Current executing thread is " + curr.getName());
URL url = FileLockThread.class.getResource("/cn/aofeng/nio/FileLockThread.txt");
RandomAccessFile raf = null;
FileChannel fc = null;
FileLock lock = null;
try {
raf = new RandomAccessFile(url.getPath(), "rw");
fc = raf.getChannel();
System.out.println(curr.getName() + " ready");
while (true) {
try {
lock = fc.lock();
break;
} catch (OverlappingFileLockException e) {
Thread.sleep(1 * 1000);
}
}
if (null != lock) {
System.out.println(curr.getName() + " get filelock success");
fc.position(fc.size());
fc.write(ByteBuffer.wrap((curr.getName() + " write data. ").getBytes()));
} else {
System.out.println(curr.getName() + " get filelock fail");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (null != lock && lock.isValid()) {
try {
lock.release();
System.out.println(curr.getName() + " release filelock");
} catch (IOException e) {
e.printStackTrace();
}
}
IOUtils.close(fc);
IOUtils.close(raf);
}
}
* @param args
*/
public static void main(String[] args) {
Thread t1 = new Thread(new FileLockThread());
t1.setName("t1");
Thread t2 = new Thread(new FileLockThread());
t2.setName("t2");
Thread t3 = new Thread(new FileLockThread());
t3.setName("t3");
t1.start();
t2.start();
t3.start();
}
}