管道用于将输出从一个程序(或线程)发送到另一个程序(或线程)的输入。 PipedInputStream
必须连接到PipedOutputStream
,而PipedOutputStream
必须连接到PipedInputStream
。
以下是使用PipedInputStream
和PipedOutputStream
的示例。 在此示例中,一个线程将数据写入管道,另一个线程从该管道读取数据。
文件:PipedStreamExample.java –
package com.yiibai.tutorial.io; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; /** * @author yiibai * PipedStreamExample.java * Nov 5, 2016 */ public class PipedStreamExample { public static void main(String[] args) throws IOException, InterruptedException { final PipedInputStream pipedInputStream=new PipedInputStream(); final PipedOutputStream pipedOutputStream=new PipedOutputStream(); /*Connect pipe*/ pipedInputStream.connect(pipedOutputStream); /*Thread for writing data to pipe*/ Thread pipeWriter=new Thread(new Runnable() { @Override public void run() { for (int i = 65; i < 91; i++) { try { pipedOutputStream.write(i); Thread.sleep(500); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } }); /*Thread for reading data from pipe*/ Thread pipeReader=new Thread(new Runnable() { @Override public void run() { for (int i = 65; i < 91; i++) { try { System.out.print((char)pipedInputStream.read()); Thread.sleep(1000); } catch (InterruptedException | IOException e) { e.printStackTrace(); } } } }); /*Start thread*/ pipeWriter.start(); pipeReader.start(); /*Join Thread*/ pipeWriter.join(); pipeReader.join(); /*Close stream*/ pipedOutputStream.close(); pipedInputStream.close(); } }
执行上面示例代码,得到以下结果:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264114.html