管道流可以用于两个线程间的通讯,管道流也分为字节流和字符流:
字节流:输入流(PipedOutputStream)和输出流(PipedInputStream)
字符流:PipedReader和PipedWriter
这里主要学习下管道的字节流PipedOutputStream和PipedInputStream
首先创建两个线程,分别作为发送者和接收者,如下:
发送者:
public class PipeSender implements Runnable {
private PipedOutputStream pout = new PipedOutputStream();
public PipedOutputStream getOutputStream(){
return pout;
}
@Override
public void run() {
String s ="接收者,你好!";
try {
pout.write(s.getBytes());//写入数据
pout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
接收者:
public class PipedReciver implements Runnable{
private PipedInputStream pin = new PipedInputStream();
public PipedInputStream getInputStream(){
return pin;
}
@Override
public void run() {
byte[] byt = new byte[1024];
try {
int len = pin.read(byt);//读出数据
String s = new String(byt,0,len);
System.out.println("收到了以下信息:"+s);
pin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试类:
public class PipedDemo {
public static void main(String[] args) throws IOException {
//创建线程对象
PipeSender psender = new PipeSender();
PipedReciver preceiver = new PipedReciver();
//调用方法,分别写入和读出数据
PipedOutputStream outputStream = psender.getOutputStream();
PipedInputStream inputStream = preceiver.getInputStream();
//将输出的数据发送到输入
outputStream.connect(inputStream);
Thread ts = new Thread(psender);
Thread tr = new Thread(preceiver);
//启动两个线程
ts.start();
tr.start();
}
}
测试结果:
收到了以下信息:接收者,你好!