public classTestRandomAccessFile {private static String FileName="aa.a";private static volatileLinux1 lx1;private static volatileLinux2 lx2;private static longfrom;private static voidclose(Closeable c){try{
c.close();
}catch(IOException ie){
ie.printStackTrace();
}
}public static classLinux1{
MappedByteBuffer buf;
RandomAccessFile raf;publicLinux1(){try{
raf= new RandomAccessFile(FileName, "rw");
buf= raf.getChannel().map(MapMode.READ_WRITE, 0, 1024*1024);
}catch(IOException ie){
ie.printStackTrace();
}new Thread(()->{try{while(true){
readAndWrite();
}
}catch(IOException e){
e.printStackTrace();
}
}).start();
}private void readAndWrite() throwsIOException {
BufferedReader reader= new BufferedReader(newInputStreamReader(System.in));
String s=reader.readLine();if(s != null){if("exit".equalsIgnoreCase(s)){
exitAll();
}else{
write(s);
}
}
}private voidwrite(String s){if(s.length() == 0)return;
buf.load();
buf.position(0);byte mark =buf.get();while(mark != 0){
buf.load();
mark=buf.get();
}if(s != null && s.length() > 0){
buf.putShort((short)s.length());for (int i = 0; i< s.length(); i++){
buf.putChar(s.charAt(i));
}
buf.position(0);
buf.put((byte)1); //加可读标记
buf.force();
from=System.nanoTime();
}
}public voidexit(){
close(raf);
}
}public static classLinux2{
MappedByteBuffer buf;
RandomAccessFile raf;publicLinux2(){try{
raf= new RandomAccessFile(FileName, "rw");
buf= raf.getChannel().map(MapMode.READ_WRITE, 0, 1024*1024);
}catch(IOException e){
e.printStackTrace();
}new Thread(()->{while(true){
checkAndRead();if(from > 0){long t = (System.nanoTime()-from);
System.out.println("time=" +t);
from= -1;
}try{
TimeUnit.NANOSECONDS.sleep(1);
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}private voidcheckAndRead(){
buf.load();if(buf.remaining() == 0)return;
buf.position(0);byte mark =buf.get();if(mark == 0)return;int len =buf.getShort();if(len > 0){char[] cs = new char[len];for (int i = 0; i< len; i++){
cs[i]=buf.getChar();
}///System.out.println("***** " + new String(cs));
}
buf.position(0);
buf.put((byte)0);
}public voidexit(){
close(raf);
}
}public static voidexitAll(){
lx1.exit();
lx2.exit();
System.exit(0);
}public static voidmain(String[] args){
lx1= newLinux1();
lx2= newLinux2();
}
}