底层_读取文件时上锁_demo

来源:互联网 发布:求生之路2游侠网络联机 编辑:程序博客网 时间:2024/06/05 20:52
package com.nio;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.FileLock;public class LockMe{    static final int LENGTH = 0x8FFFFFF;// 128M文件    static FileChannel fc;    @SuppressWarnings("resource")    public static void main(String[] args)        throws Exception    {        fc = new RandomAccessFile("lockTest", "rw").getChannel();        MappedByteBuffer out = fc.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);        for (int i = 0; i < LENGTH; i++)        {            out.put((byte)'x');        }        new MyThread(out, 0, 0 + LENGTH / 3);        new MyThread(out, LENGTH / 2, LENGTH / 2 + LENGTH / 4);    }    private static class MyThread extends Thread    {        private ByteBuffer buff;        private int start, end;        MyThread(ByteBuffer bb, int start, int end)        {            super();            this.start = start;            this.end = end;            bb.limit(end);            bb.position(start);            buff = bb.slice();            start();        }        @Override        public void run()        {            try            {                // get lock                FileLock fl = fc.lock(start, end, false);                System.out.println("Locked " + start + " to " + end);                // execute                while (buff.position() < buff.limit() - 1)                    buff.put((byte)(buff.get() + 1));                // 释放锁                fl.release();                System.out.println("Release " + start + " to " + end);            }            catch (Exception e)            {                e.printStackTrace();            }        }    }}
0 0
原创粉丝点击