📅  最后修改于: 2020-09-27 08:17:13             🧑  作者: Mango
PipedInputStream和PipedOutputStream类可用于同时读取和写入数据。两个流使用PipedOutputStream类的connect()方法相互连接。
在这里,我们创建了两个线程t1和t2。 t1线程使用PipedOutputStream对象写入数据,而t2线程使用PipedInputStream对象从该管道读取数据。两个管道流对象都相互连接。
import java.io.*;
class PipedWR{
public static void main(String args[])throws Exception{
final PipedOutputStream pout=new PipedOutputStream();
final PipedInputStream pin=new PipedInputStream();
pout.connect(pin);//connecting the streams
//creating one thread t1 which writes the data
Thread t1=new Thread(){
public void run(){
for(int i=65;i<=90;i++){
try{
pout.write(i);
Thread.sleep(1000);
}catch(Exception e){}
}
}
};
//creating another thread t2 which reads the data
Thread t2=new Thread(){
public void run(){
try{
for(int i=65;i<=90;i++)
System.out.println(pin.read());
}catch(Exception e){}
}
};
//starting both threads
t1.start();
t2.start();
}}