PipedInputStream和PipedOutputStream
输入输出可以直接进行连接,通过结合线程使用;
用生产者消费者举例
package com.javaxl.io.other;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* @author 小李飞刀
* @site www.javaxl.com
* @company
* @create 2019-06-16 9:10
*/
public class PipedStreamDemo {
public static void main(String[] args) throws IOException {
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
in.connect(out);
Read r = new Read(in);
Write w = new Write(out);
new Thread(r).start();
new Thread(w).start();
}
}
class Read implements Runnable{
private PipedInputStream in;
Read(PipedInputStream in){
this.in = in;
}
@Override
public void run() {
try {
byte[] buf = new byte[1024];
System.out.println("独取前...没有数据阻塞");
int len = in.read(buf);
System.out.println("读取数据...阻塞结束");
String s = new String(buf,0,len);
System.out.println(s);
in.close();
} catch (IOException e) {
throw new RuntimeException("管道读取流失败!!!");
}
}
}
class Write implements Runnable{
private PipedOutputStream out;
Write(PipedOutputStream out){
this.out = out;
}
@Override
public void run() {
try {
System.out.println("开始写入数据,等待6秒后...");
Thread.sleep(6000);
out.write("piped 来啦".getBytes());
out.close();
} catch (Exception e) {
throw new RuntimeException("管道输出流失败!!!");
}
}
}
在这个例子中,输出流是作为生产者,输入流是作为消费者,它们操作的是同一个资源;
当输入流没有读取到数据时,消费者对应的线程释放cpu执行权,进入阻塞状态,输出流对应的生产者会抢到cpu执行权,生产数据。这时管道流中就有数据了,消费者对应的线程就被唤醒,继续执行下面代码。
运行截图
Cpu先执行到写入线程

Cpu先执行读取线程

备案号:湘ICP备19000029号
Copyright © 2018-2019 javaxl晓码阁 版权所有