Java进程间传递返回_使用RandomAccessFile在两个java进程之间传递数据

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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值