流----管道流 PipedInputStream()/PipedOutStream()

管道流可以实现两个线程之间二级制数据的传输,二进制数据的传输通常要两个不同的线程来控制它们:

线程与流的使用实例(网上copy的)

package servlet;

import java.io.IOException;  
import java.io.PipedInputStream;  
import java.io.PipedOutputStream;  
 
public class PipedInputStreamTest {  
 
   public static void main(String[] args) {  
       //管道输出流  
       PipedOutputStream out = new PipedOutputStream();  
       //管道输入流  
       PipedInputStream in = null;  
       try {  
           //连接两个管道流。或者调用connect(Piped..);方法也可以  
           in = new PipedInputStream(out);  
           Thread read = new Thread(new Read(in));  
           Thread write = new Thread(new Write(out));  
           //启动线程  
           read.start();  
           write.start();  
       } catch (IOException e) {  
           e.printStackTrace();  
       }  
   }  
}  
 
class Write implements Runnable {  
   PipedOutputStream pos = null;  
 
   public Write(PipedOutputStream pos) {  
       this.pos = pos;  
   }  
 
   public void run() {  
       try {  
           System.out.println("程序将在3秒后写入数据,请稍等。。。");  
           Thread.sleep(3000);  
           pos.write("wangzhihong".getBytes());  
           pos.flush();  
       } catch (IOException e) {  
           e.printStackTrace();  
       } catch (InterruptedException e) {  
           e.printStackTrace();  
       } finally {  
           try {  
               if (pos != null) {  
                   pos.close();  
               }  
           } catch (IOException e) {  
               e.printStackTrace();  
           }  
       }  
   }  
}  
 
class Read implements Runnable {  
   PipedInputStream pis = null;  
 
   public Read(PipedInputStream pis) {  
       this.pis = pis;  
   }  
 
   public void run() {  
       byte[] buf = new byte[1024];  
       try {  
           pis.read(buf);  
           System.out.println(new String(buf));  
       } catch (IOException e) {  
           e.printStackTrace();  
       } finally {  
           try {  
               if (pis != null) {  
                   pis.close();  
               }  
           } catch (IOException e) {  
               e.printStackTrace();  
           }  
       }  
   }  
}  

你可能感兴趣的:(流----管道流 PipedInputStream()/PipedOutStream())