1. 管道流
- 管道流用于实现线程之间的数据交互, 但通常来说这个并不使用.
- 管道流根据输入输出和字节字符类型一共有四种:
PipedInputStream
PipedOutputStream
PipedReader
PipedWriter
1.1. 操作实例
定义 A 线程
//A线程发送数据给B线程 class AThread extends Thread{ private PipedOutputstream out = new PipedOutputStream(); //定义方法用以返回线程的管道输出流 public PipedOutputStream getOut(){ return out; } public void run(){ try { //在管道流中写入26个字母 for(int i = 65; i < 65 + 26; i++) out.write(i); out.c1ose() ; }catch(IOException e){ e.printstackTrace(); } } }
定义 B 线程
//B线程接受A线程发送的数据 class BThread extends Thread{ PipedInputStream in = null; public BThread (AThread aThread) throws Exception{ //获取并包装A线程的管道输出流 in = new PipedInputStream(aThread.getOut()); } public void run(){ int len= -1; try{ //打印从A线程的管道流中获取的内容 while((len = in.read()) != -1){ System.out.println((char)len) ; } in.close(); } catch(IOException e){ e.printstackTrace() ; } } }
主方法
public class PipedStreamDemo{ public static void main(String[] args){ AThread a = new AThread(); BThread b = new BThread(a); //线程开始后, 最终控制台会输出26个字母 a.start(); b.start(); } }