线程通信之管道流

原文链接: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.  

  5. public class PipedInputStreamTest {  

  6.  

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

  8.        //管道输出流  

  9.        PipedOutputStream out = new PipedOutputStream();  

  10.        //管道输入流  

  11.        PipedInputStream in = null;  

  12.        try {  

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

  14.            in = new PipedInputStream(out);  

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

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

  17.            //启动线程  

  18.            read.start();  

  19.            write.start();  

  20.        } catch (IOException e) {  

  21.            e.printStackTrace();  

  22.        }  

  23.    }  

  24. }  

  25.  

  26. class Write implements Runnable {  

  27.    PipedOutputStream pos = null;  

  28.  

  29.    public Write(PipedOutputStream pos) {  

  30.        this.pos = pos;  

  31.    }  

  32.  

  33.    public void run() {  

  34.        try {  

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

  36.            Thread.sleep(3000);  

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

  38.            pos.flush();  

  39.        } catch (IOException e) {  

  40.            e.printStackTrace();  

  41.        } catch (InterruptedException e) {  

  42.            e.printStackTrace();  

  43.        } finally {  

  44.            try {  

  45.                if (pos != null) {  

  46.                    pos.close();  

  47.                }  

  48.            } catch (IOException e) {  

  49.                e.printStackTrace();  

  50.            }  

  51.        }  

  52.    }  

  53. }  

  54.  

  55. class Read implements Runnable {  

  56.    PipedInputStream pis = null;  

  57.  

  58.    public Read(PipedInputStream pis) {  

  59.        this.pis = pis;  

  60.    }  

  61.  

  62.    public void run() {  

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

  64.        try {  

  65.            pis.read(buf);  

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

  67.        } catch (IOException e) {  

  68.            e.printStackTrace();  

  69.        } finally {  

  70.            try {  

  71.                if (pis != null) {  

  72.                    pis.close();  

  73.                }  

  74.            } catch (IOException e) {  

  75.                e.printStackTrace();  

  76.            }  

  77.        }  

  78.    }  

  79. }  

  80.  

posted @ 2016-10-19 10:10  ZSQ的博客  阅读(922)  评论(0编辑  收藏  举报