- import java.io.*;
- class Read implements Runnable
- {
- private PipedInputStream pis;
- public Read(PipedInputStream pis)
- {
- this.pis=pis;
- }
- public void run()
- {
- byte[] buf=new byte[1024];
- int len=0;
- System.out.println("开始读取数据!");
- try
- {
- len=pis.read(buf);
- }
- catch (IOException e)
- {
- throw new RuntimeException("读取数据失败!");
- }
- System.out.println("数据读取完毕!");
- System.out.println(new String(buf,0,len));
- }
- }
- class Write implements Runnable
- {
- private PipedOutputStream pos;
- public Write(PipedOutputStream pos)
- {
- this.pos=pos;
- }
- public void run()
- {
- System.out.println("5秒后写入数据,进入阻塞!");
- try
- {
- Thread.sleep(5000);
- }
- catch (InterruptedException e)
- {
- e.getMessage();
- }
- try
- {
- pos.write("hehehe".getBytes());
- }
- catch (IOException e)
- {
- throw new RuntimeException("数据写出失败!");
- }
- System.out.println("数据写入完毕,解除阻塞!");
- }
- }
- class PipedStreamDemo
- {
- public static void main(String[] args)
- {
- PipedInputStream pis=null;
- PipedOutputStream pos=null;
- try
- {
- pis=new PipedInputStream();
- pos=new PipedOutputStream();
- pos.connect(pis);
- }
- catch (IOException e)
- {
- throw new RuntimeException("管道连接失败!");
- }
- new Thread(new Write(pos)).start();
- new Thread(new Read(pis)).start();
- }
- }
复制代码 到底是管道输出到输入,还是输入到输出
|
|