java学习笔记 管道流
管道流管道流主要作用是可以连接两个线程间的通信。管道流也分为字节流(PipedInputStream、PipedOutputStream)与字符流(PipedReader、PipedWriter)两种类型.
一个PipedInputStream 对象必须和一个PipedOutputStream 对象进行连接而产生一个通信管道,PipedOutputStream 可以向管道中写入数据,PipedInputStream 可以从管道中读取 PipedOutputStream 写入的数据。
管道实现线程间通信图解
代码实例:
Sender类: import java.io.IOException; import java.io.PipedOutputStream; public class Sender extends Thread { private PipedOutputStream out =null; public PipedOutputStream getOutputStream() { this.out=new PipedOutputStream(); return out; } public void run() { String s = new String("Receiver,你好!"); try { out.write( s.getBytes() ); out.close(); } catch (IOException e) { System.out.println( e.getMessage() ); } } } Eeceiver类: import java.io.IOException; import java.io.PipedInputStream; public class Eeceiver extends Thread { privatePipedInputStream in = new PipedInputStream(); publicPipedInputStream getinputStream() { return in; } publicvoid run ( ) { String s = null; byte [] buf = new byte[1024]; try { int len = in.read( buf ); s= new String( buf,0,len); System.out.println("收到了一下消息:"+s); in.close(); } catch (IOException e) { System.out.println( e.getMessage() ); } } } Pipedemo 类: import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; public class pipedemo { publicstatic void main( String args[]) { try{ Sendersender = new Sender(); Eeceiverreceiver = new Eeceiver(); PipedOutputStreamout = sender.getOutputStream(); PipedInputStreamin = receiver.getinputStream(); out.connect(in); sender.start(); receiver.start(); } catch (IOException e) { System.out.println(e.getMessage() ); } } }
补充:软件开发 , Java ,