管道流,用于线程间的通信。一个线程的PipedInputStream对象从另外一个线程的PipedOutputStream对象读取输入。要使管道流有用,必须同时构造管道输入流和管道输出流。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
import
java.io.IOException;
import java.io.PipedOutputStream;
public class Producer extends Thread {
private PipedOutputStream pos;
public Producer(PipedOutputStream pos) {
this .pos = pos;
}
@Override
public void run() {
super .run();
try {
pos.write( " Hello " .getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.PipedOutputStream;
public class Producer extends Thread {
private PipedOutputStream pos;
public Producer(PipedOutputStream pos) {
this .pos = pos;
}
@Override
public void run() {
super .run();
try {
pos.write( " Hello " .getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
import
java.io.IOException;
import java.io.PipedInputStream;
public class Consumer extends Thread {
private PipedInputStream pis;
public Consumer(PipedInputStream pis) {
this .pis = pis;
}
@Override
public void run() {
super .run();
byte [] b = new byte [ 100 ]; // 将数据保存在byte数组中
try {
int len = pis.read(b); // 从数组中得到实际大小。
System.out.println( new String(b, 0 , len));
pis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.PipedInputStream;
public class Consumer extends Thread {
private PipedInputStream pis;
public Consumer(PipedInputStream pis) {
this .pis = pis;
}
@Override
public void run() {
super .run();
byte [] b = new byte [ 100 ]; // 将数据保存在byte数组中
try {
int len = pis.read(b); // 从数组中得到实际大小。
System.out.println( new String(b, 0 , len));
pis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
import
java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStreamTest {
public static void main(String[] args) {
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
try {
pos.connect(pis); // 连接管道
new Producer(pos).start(); // 启动线程
new Consumer(pis).start(); // 启动线程
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStreamTest {
public static void main(String[] args) {
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
try {
pos.connect(pis); // 连接管道
new Producer(pos).start(); // 启动线程
new Consumer(pis).start(); // 启动线程
} catch (IOException e) {
e.printStackTrace();
}
}
}