线程通信之管道流

原文链接:http://www.bdqn.cn/news/201303/8270.shtml

管道流可以实现两个线程之间,二进制数据的传输。

管道流就像一条管道,一端输入数据,别一端则输出数据。通常要分别用两个不同的线程来控制它们。

使用方法如下:

[html] view plaincopy
 
  1. import java.io.IOException;  

  2. import java.io.PipedInputStream;  

  3. import java.io.PipedOutputStream;  

  4. public class PipedInputStreamTest {  

  5.    public static void main(String[] args) {  

  6.        //管道输出流  

  7.        PipedOutputStream out = new PipedOutputStream();  

  8.        //管道输入流  

  9.        PipedInputStream in = null;  

  10.        try {  

  11.            //连接两个管道流。或者调用connect(Piped..);方法也可以  

  12.            in = new PipedInputStream(out);  

  13.            Thread read = new Thread(new Read(in));  

  14.            Thread write = new Thread(new Write(out));  

  15.            //启动线程  

  16.            read.start();  

  17.            write.start();  

  18.        } catch (IOException e) {  

  19.            e.printStackTrace();  

  20.        }  

  21.    }  

  22. }  

  23. class Write implements Runnable {  

  24.    PipedOutputStream pos = null;  

  25.    public Write(PipedOutputStream pos) {  

  26.        this.pos = pos;  

  27.    }  

  28.    public void run() {  

  29.        try {  

  30.            System.out.println("程序将在3秒后写入数据,请稍等。。。");  

  31.            Thread.sleep(3000);  

  32.            pos.write("wangzhihong".getBytes());  

  33.            pos.flush();  

  34.        } catch (IOException e) {  

  35.            e.printStackTrace();  

  36.        } catch (InterruptedException e) {  

  37.            e.printStackTrace();  

  38.        } finally {  

  39.            try {  

  40.                if (pos != null) {  

  41.                    pos.close();  

  42.                }  

  43.            } catch (IOException e) {  

  44.                e.printStackTrace();  

  45.            }  

  46.        }  

  47.    }  

  48. }  

  49. class Read implements Runnable {  

  50.    PipedInputStream pis = null;  

  51.    public Read(PipedInputStream pis) {  

  52.        this.pis = pis;  

  53.    }  

  54.    public void run() {  

  55.        byte[] buf = new byte[1024];  

  56.        try {  

  57.            pis.read(buf);  

  58.            System.out.println(new String(buf));  

  59.        } catch (IOException e) {  

  60.            e.printStackTrace();  

  61.        } finally {  

  62.            try {  

  63.                if (pis != null) {  

  64.                    pis.close();  

  65.                }  

  66.            } catch (IOException e) {  

  67.                e.printStackTrace();  

  68.            }  

  69.        }  

  70.    }  

  71. }  

原文地址:https://www.cnblogs.com/zhongshiqiang/p/5976206.html