zoukankan      html  css  js  c++  java
  • Java线程间通信:使用管道

    管道输入/输出流和普通的文件输入/输出流或者网络输入/输出流不同之处在于,它主要用于线程之间的数据传输,而传输的媒介为内存。

    管道输入/输出流主要包括了如下4种具体实现:PipedOutputStream、PipedInputStream、PipedReader和PipedWriter,前两种面向字节,而后两种面向字符。

    package gj.concurrent.sync;
    
    import java.io.IOException;
    import java.io.PipedReader;
    import java.io.PipedWriter;
    
    /**
     * Author: areful
     */
    public class PipedSync {
        private static class Writer implements Runnable {
            private PipedWriter out;
    
            private Writer(PipedWriter writer) {
                out = writer;
            }
    
            @Override
            public void run() {
                int receive;
                try {
                    while ((receive = System.in.read()) != -1) {
                        out.write(receive);
                    }
                } catch (Exception ignored) {
                } finally {
                    try {
                        out.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    
        private static class Printer implements Runnable {
            private PipedReader in;
    
            private Printer(PipedReader in) {
                this.in = in;
            }
    
            public void run() {
                int receive;
                try {
                    while ((receive = in.read()) != -1) {
                        System.out.print((char) receive);
                    }
                } catch (IOException ignored) {
                }
            }
        }
    
        public static void main(String[] args) throws Exception {
            PipedWriter out = new PipedWriter();
            PipedReader in = new PipedReader();
            out.connect(in);
    
            Thread printThread = new Thread(new Printer(in), "PrintThread");
            printThread.start();
    
            Thread writeThread = new Thread(new Writer(out), "WriteThread");
            writeThread.start();
        }
    }
    

      

  • 相关阅读:
    python之os模块
    python之字符串
    python之爬虫(beautifulsoup)
    python之常见算法
    python之装饰器(类装饰器,函数装饰器)
    python之mock使用,基于unittest
    python之定时器
    python基础语法随记
    redis基础
    移动端页面开发(二)
  • 原文地址:https://www.cnblogs.com/areful/p/10396181.html
Copyright © 2011-2022 走看看