- package cn.study.io;
- import java.io.IOException;
- import java.io.PipedInputStream;
- import java.io.PipedOutputStream;
- public class PipedStreamDemo {
- /**
- * @param args
- * @throws IOException
- */
- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- final PipedInputStream pis = new PipedInputStream();
- final PipedOutputStream pos = new PipedOutputStream();
-
- Thread read = new Thread(){
- public void run(){
- try {
- byte[] buf = new byte[1024];
- System.out.println("读取前,没有数据,等待...");
- int len = pis.read(buf);
- System.out.println("读到数据,打印数据...");
- String str = new String(buf,0,len);
- System.out.println(str);
- pis.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- };
-
- Runnable write = new Runnable(){
- public void run(){
- try {
- System.out.println("开始写入数据,等待6秒后...");
- Thread.sleep(6000);
- pos.write("piped lai la".getBytes());
- pos.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- };
- pis.connect(pos);
- read.start();
- new Thread(write).start();
- }
- }
复制代码 |