- public class TestRandomAccessFile {
- private staticString FileName="aa.a";
- private static volatile Linux1 lx1;
- private static volatile Linux2 lx2;
- private static long from;
- private static void close(Closeable c){
- try{
- c.close();
- }catch(IOException ie){
- ie.printStackTrace();
- }
- }
- public static class Linux1{
- MappedByteBuffer buf;
- RandomAccessFile raf;
- public Linux1(){
- try{
- raf =newRandomAccessFile(FileName, "rw");
- buf = raf.getChannel().map(MapMode.READ_WRITE, 0, 1024*1024);
- }catch(IOException ie){
- ie.printStackTrace();
- }
- newThread(()->{
- try{
- while(true){
- readAndWrite();
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- }).start();
- }
- private voidreadAndWrite()throws IOException {
- BufferedReader reader =newBufferedReader(new InputStreamReader(System.in));
- String s = reader.readLine();
- if(s !=null){
- if("exit".equalsIgnoreCase(s)){
- exitAll();
- }else{
- write(s);
- }
- }
- }
- private void write(String s){
- if(s.length() == 0)return;
- buf.load();
- buf.position(0);
- bytemark = buf.get();
- while(mark != 0){
- buf.load();
- mark = buf.get();
- }
- if(s !=null&& s.length() > 0){
- buf.putShort((short)s.length());
- for(inti = 0; i< s.length(); i++){
- buf.putChar(s.charAt(i));
- }
- buf.position(0);
- buf.put((byte)1);//加可读标记
- buf.force();
- from = System.nanoTime();
- }
- }
- public void exit(){
- close(raf);
- }
- }
- public static class Linux2{
- MappedByteBuffer buf;
- RandomAccessFile raf;
- public Linux2(){
- try{
- raf =newRandomAccessFile(FileName, "rw");
- buf = raf.getChannel().map(MapMode.READ_WRITE, 0, 1024*1024);
- }catch(IOException e){
- e.printStackTrace();
- }
- newThread(()->{
- while(true){
- checkAndRead();
- if(from > 0){
- longt = (System.nanoTime()-from);
- System.out.println("time=" + t);
- from = -1;
- }
- try{
- TimeUnit.NANOSECONDS.sleep(1);
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }).start();
- }
- private void checkAndRead(){
- buf.load();
- if(buf.remaining() == 0)return;
- buf.position(0);
- bytemark = buf.get();
- if(mark == 0)return;
- intlen = buf.getShort();
- if(len > 0){
- char[] cs =new char[len];
- for(inti = 0; i< len; i++){
- cs[i] = buf.getChar();
- }
- // /System.out.println("***** " + new String(cs));
- }
- buf.position(0);
- buf.put((byte)0);
- }
- public void exit(){
- close(raf);
- }
- }
- public static void exitAll(){
- lx1.exit();
- lx2.exit();
- System.exit(0);
- }
- public static void main(String[] args){
- lx1 =new Linux1();
- lx2 =new Linux2();
- }
- }
来源: http://www.cnblogs.com/xuhengjs/p/6767919.html