管道流Demo

PipedInputStream 和 PipedOutputStream 用于在程序中创建管道通信,两者结合可以完成线程之间的通信。

下面是一个简单的例子:


package IO;


import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;


public class PipedStreamTest {
public static void main(String[] args) throws Exception {


Sender s = new Sender();
Receiver r = new Receiver();

PipedOutputStream outputStream = s.getOutputStream();
PipedInputStream inputStream = r.getInputStream();

outputStream.connect(inputStream);//管道连接。顺序随意

s.start();
r.start();
}
}
//发送器要发送数据,定义一个PipeOutputStream
class Sender extends Thread {

private PipedOutputStream out = new PipedOutputStream();

public PipedOutputStream getOutputStream() {
return out;
}

@Override
public void run() {
String str = "Hello PipedInputStream,Im PipedOutputStream";
try {
out.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


//接收器
class Receiver extends Thread {
private PipedInputStream in = new PipedInputStream();
public PipedInputStream getInputStream() {
return in;
}
@Override
public void run() {
byte[] buf = new byte[1024];
try {
int len = in.read(buf);
String str = new String(buf, 0, len);
System.out.println("收到信息:"+str);

} catch (IOException e) {
e.printStackTrace();
}
}
}

你可能感兴趣的:(javaSE)