PipeStream是一种特殊的管道流,可以提供不同线程之间传送数据,一个线程发送数据到输出管道,另一个线程从输入管道读数据。
通常,数据由某个线程从 PipedInputStream 对象读取,并由其他线程将其写入到相应的 PipedOutputStream。不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。管道输入流包含一个缓冲区,可在缓冲区限定的范围内将读操作和写操作分离开。
package com.example.test;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Test234 {
public static void main(String[] args) {
PipedInputStream in= new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
try {
in.connect(out);//必须先连接,可以不调用该方法,用PipedInputStream 的构造函数,直接传一个PipedOutputStream ,它会自动帮你连接。
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Mythread234t mt = new Mythread234t(in,out);
Thread t1 = new Thread(mt);
t1.setName("t1");
Thread t2 = new Thread(mt);
t2.setName("t2");
t1.start();
t2.start();
}
public void writeData(PipedOutputStream out) {
for(int i = 0;i<100;i++) {
try {
out.write((byte)i);
System.out.println("jjj"+(byte)i);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readData(PipedInputStream in) {
byte[] b = new byte[20];
try {
int len = in.read();
while(len!=-1) {
System.out.println(""+len);
len = in.read();
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Mythread234t implements Runnable{
Test234 t = new Test234();
PipedInputStream in;
PipedOutputStream out;
public Mythread234t(PipedInputStream in, PipedOutputStream out) {
super();
this.in = in;
this.out = out;
}
@Override
public void run() {
// TODO Auto-generated method stub
if(Thread.currentThread().getName().equals("t1")) {
t.readData(in);
}
else {
t.writeData(out);
}
}
}
PipeReader和PipeWriter和上面这种类似,只是用在字符的处理上,就不在说明。