zoukankan      html  css  js  c++  java
  • Java IO学习6:管道流

    管道流(线程通信流)

    管道流的主要作用是可以进行两个线程间的通讯,分为管道输出流(PipedOutputStream)、管道输入流(PipedInputStream),如果想要进行管道输出,则必须要把输出流连在输入流之上,在PipedOutputStream类上有如下的一个方法用于连接管道:

    public void connect(PipedInputStream snk)throws IOException

    例子:线程之间用管道流进行通讯

    复制代码
     1 import java.io.IOException;
    2 import java.io.PipedInputStream;
    3 import java.io.PipedOutputStream;
    4
    5 class Send implements Runnable{
    6
    7 private PipedOutputStream pos;//管道输出流
    8 public Send(){
    9 pos=new PipedOutputStream();
    10 }
    11 @Override
    12 public void run() {
    13 String str="Hello World!";
    14 try {
    15 pos.write(str.getBytes());
    16 } catch (IOException e) {
    17 e.printStackTrace();
    18 }
    19 try {
    20 pos.close();
    21 } catch (IOException e) {
    22 e.printStackTrace();
    23 }
    24 }
    25 public PipedOutputStream getPos() {
    26 return pos;
    27 }
    28 }
    29
    30 class Receive implements Runnable{
    31
    32 private PipedInputStream pis;//管道输入流
    33 public Receive(){
    34 pis=new PipedInputStream();
    35 }
    36 @Override
    37 public void run() {
    38 byte[] b=new byte[1024];
    39 int len=0;
    40 try {
    41 len=pis.read(b);
    42 } catch (IOException e) {
    43 e.printStackTrace();
    44 }
    45 try {
    46 pis.close();
    47 } catch (IOException e) {
    48 e.printStackTrace();
    49 }
    50 System.out.println(new String(b,0,len));
    51 }
    52 public PipedInputStream getPis() {
    53 return pis;
    54 }
    55 }
    56
    57 public class Test23 {
    58 public static void main(String[] args) {
    59 Send send=new Send();
    60 Receive receive=new Receive();
    61 try {
    62 send.getPos().connect(receive.getPis());//连接管道
    63 } catch (IOException e) {
    64 e.printStackTrace();
    65 }
    66 new Thread(send).start();//启动线程
    67 new Thread(receive).start();//启动线程
    68 }
    69 }
    复制代码
    Face your past without regret. Handle your present with confidence.Prepare for future without fear. keep the faith and drop the fear. 面对过去无怨无悔,把握现在充满信心,备战未来无所畏惧。保持信念,克服恐惧!一点一滴的积累,一点一滴的沉淀,学技术需要不断的积淀!
  • 相关阅读:
    EL表达式
    使用Cookie保存用户信息
    GUI学习之二——PyQt控件初识
    GUI学习之一——PyQt5初识
    HTML学习总结
    centos7 mysql的安装与配置
    Python之RabbitMQ的使用
    python之模块的导入
    Python之ftp服务器
    GUI学习之〇——PyQt5安装
  • 原文地址:https://www.cnblogs.com/200911/p/2707609.html
Copyright © 2011-2022 走看看