普通输入输出流必须通过变量或者数组中转。而管道输入输出流可以直接关联。管道流要结合多线程使用。因为read()会阻塞,如果输入输出流在同一个线程,read()没有数据一直等待,造成死锁。管道输入流提供要写入管道输出流的所有数据字节。
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedDemo {
public static void main(String[] args) throws IOException {
PipedInputStream input = new PipedInputStream();
PipedOutputStream output = new PipedOutputStream();
input.connect(output);
new Thread(new Input(input)).start();
new Thread(new Output(output)).start();
}
}
class Input implements Runnable{ //没有输入源,此处会导致死锁
private PipedInputStream in;
Input(PipedInputStream in){
this.in = in;
}
public void run() {
byte[] buffer = new byte[1024];
int len = 0;
try {
len = in.read(buffer);
String s = new String(buffer,0,len);
System.out.println("s="+s);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Output implements Runnable{
private PipedOutputStream out;
Output(PipedOutputStream out){
this.out = out;
}
public void run() {
System.out.println("run");
}
}
本文介绍Java中管道输入输出流(PipedInputStream和PipedOutputStream)的使用方法,以及如何结合多线程避免死锁问题。通过示例代码展示了如何在两个线程间直接传递数据,避免了传统IO流需要通过变量或数组中转的问题。
367

被折叠的 条评论
为什么被折叠?



