管道流的主要作用是可以进行两个线程间的通信
分为管道输出流(PipedOutputStream)和管道输入流(PipedInputStream)
定义两个线程对象,在发送的线程类中定义了管道输出类,在接收的线程类中定义了管道的输入类,在操作时只需要使用PipedOutputStream类中提供的connection()方法就可以将两个线程冠带连接在一起,线程启动后会自动进行管道的输入和输出操作
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
//=================================================
// File Name : Pipe_demo
//------------------------------------------------------------------------------
// Author : Common
// 类名:Send
// 属性:
// 方法:
class Send implements Runnable{ //实现Runnable接口
private PipedOutputStream pos = null; //管道输出流
public Send() { //实例化输出流
super();
this.pos = new PipedOutputStream();
}
public PipedOutputStream getPos() { //通过线程类得到输出流
return pos;
}
@Override
public void run() {
// TODO 自动生成的方法存根
String str = "HelloWord!!";
try{
this.pos.write(str.getBytes()); //输出信息
}catch(IOException e){
e.printStackTrace();
}
try{
this.pos.close(); //关闭输出流
}catch(IOException e){
e.printStackTrace();
}
}
}
//类名:Receive
//属性:
//方法:
class Receive implements Runnable{ //实现Runnable接口
private PipedInputStream pis = null; //管道输入流
public Receive() { //实例化输出流
super();
this.pis = new PipedInputStream();
}
public PipedInputStream getPis() { //通过线程类得到输入流
return pis;
}
@Override
public void run() {
// TODO 自动生成的方法存根
byte b[] = new byte[1024]; //实例化输入流
int len = 0;
try{
len = this.pis.read(b); //接收数据
}catch(IOException e){
e.printStackTrace();
}
try{
this.pis.close(); //关闭输入流
}catch(IOException e){
e.printStackTrace();
}
System.out.println("接收的内容为"+new String(b,0,len));
}
}
//主类
//Function : Pipe_demo
public class Pipe_demo {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Send s = new Send();
Receive r = new Receive();
try{
s.getPos().connect(r.getPis()); //连接管道
}catch(IOException e){
e.printStackTrace();
}
new Thread(s).start();
new Thread(r).start();
}
}