PipedInputStream和PipedOutputStream顾名思义,管道流,管道流和多线程相结合,因为管道输入流需要和管道输出流相连接,连接之后如果输入流先执行,输出流后执行,一开始的时候管道里并没有字节流存在,因此read会无法执行,导致程序无法运行,因此管道流必须和多线程相结合。
附上代码:
```
import java.io.*;
public class PipedStream {
public static void main(String[] args) throws IOException {
// TODO 自动生成的方法存根
PipedInputStream pis=new PipedInputStream();
PipedOutputStream pos=new PipedOutputStream();
pis.connect(pos);//连接管道
new Thread(new Input(pis)).start(); //创建输入流线程
new Thread(new Output(pos)).start();//创建输出流线程
}
}
class Input implements Runnable{
private PipedInputStream in;
public Input(PipedInputStream in) {
// TODO 自动生成的构造函数存根
this.in=in;
}
public void run(){
try {
byte[] buf=new byte[1024];
System.out.println("读取开始");
int len=in.read();
System.out.println(new String(buf,0,len));
in.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
throw new RuntimeException("读取管道失败");
}
}
}
class Output implements Runnable{
private PipedOutputStream out;
Output(PipedOutputStream out){
this.out=out;
}
public void run(){
try {
System.out.println("写入开始");
Thread.sleep(1000); //为了避免线程死等,可以将这个线程挂起,切换线程执行
out.write("hello piper".getBytes());
out.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
throw new RuntimeException("管道写入失败");
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
throw new RuntimeException("线程出问题了");
}
}
}
接下来的时间会将框架知识还有多线程知识还有异常知识陆续写入进来。