码迷,mamicode.com
首页 > 编程语言 > 详细

JavaIO流学习总结-PipedReader和PipedWriter基本操作练习

时间:2020-04-05 17:01:51      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:details   rac   read   art   str   输入输出   输出   print   his   

package io;
import java.io.*;
/*
 * 修改日期:2020/04/05
 * 修改人:牟松
 * 管道流(字节流)PipedReader和PipedWriter基本操作练习
 * 参考链接:https://blog.csdn.net/sk199048/article/details/51260757
 */
class Producer extends Thread {
    private PipedWriter writer = new PipedWriter();
   
    public Producer(PipedWriter writer) {
        this.writer = writer;
    }
    @Override
    public void run() {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("Hello World!");
            writer.write(sb.toString());
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Consumer extends Thread{
    private PipedReader reader = new PipedReader();
    public Consumer(PipedReader reader) {
        this.reader = reader;
    }
    @Override
    public void run() {
        try {
            char [] cbuf = new char[20];
            reader.read(cbuf, 0, cbuf.length);       
            System.out.println("管道流中的数据为: " + new String(cbuf));
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public class ceshi {
   public static void main(String[] args)
     { 
     /**
      * 线程间通过管道流通信的步骤为
      * 1 建立输入输出流
      * 2 绑定输入输出流
      * 3 Writer写
      * 4 Reader读
      */
     PipedReader reader = new PipedReader();
     PipedWriter writer = new PipedWriter();
     Producer producer = new Producer(writer);
     Consumer consumer = new Consumer(reader);
     try {
         writer.connect(reader);
         producer.start();
         consumer.start();
     } catch (Exception e) {
         e.printStackTrace();
     }
     }
}

JavaIO流学习总结-PipedReader和PipedWriter基本操作练习

标签:details   rac   read   art   str   输入输出   输出   print   his   

原文地址:https://www.cnblogs.com/musong1998/p/12637881.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!