java 多线程使用PipedOutStream和PipedInputStream
packagetest;importjava.io.PipedInputStream;importjava.io.PipedOutputStream;publicclassPipeTest{publicstaticvoidmain(String[]args)throwsException{PipedOutputStreampos=newPipedOutputStream();PipedInputStreampis=newPipedInputStream();//链接pis.connect(pos);//写线程InThreadit=newInThread(pos,pis);//读线程OutThreadot=newOutThread(pos,pis);it.start();ot.start();Thread.sleep(1000);}}classInThreadextendsThread{PipedOutputStreampos=null;PipedInputStreampis=null;InThread(PipedOutputStreampos,PipedInputStreampis){this.pos=pos;this.pis=pis;}publicvoidrun(){try{//写入数据byte[]b=newString("thisisatest!").getBytes();pos.write(b);//关闭链接,此处必须关闭,不然会包异常pos.close();}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}classOutThreadextendsThread{PipedInputStreampis=null;PipedOutputStreampos=null;OutThread(PipedOutputStreampos,PipedInputStreampis){this.pis=pis;this.pos=pos;}publicvoidrun(){//读取数据Stringm="";byte[]b=newbyte[1024];try{intlen;len=pis.read(b);m=m+newString(b);while(len!=-1){len=pis.read(b);m=m+newString(b);}//关闭资源pis.close();System.out.println(m);}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。