管道流:
实现两个线程之间的数据交互. PipedInputStream PipedOutputStream PipedReder
PipedWriter
中文API解释:
PipedInputStream
public class PipedInputStreamextends InputStream管道输入流应该连接到管道输出流;管道输入流提供要写入管道输出流的所有数据字节。通常,数据由某个线程从 PipedInputStream 对象读取,并由其他线程将其写入到相应的 PipedOutputStream。不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。管道输入流包含一个缓冲区,可在缓冲区限定的范围内将读操作和写操作分离开。如果向连接管道输出流提供数据字节的线程不再存在,则认为该管道已损坏。
PipedOutputStream
public class PipedOutputStreamextends OutputStream可以将管道输出流连接到管道输入流来创建通信管道。管道输出流是管道的发送端。通常,数据由某个线程写入 PipedOutputStream 对象,并由其他线程从连接的 PipedInputStream 读取。不建议对这两个对象尝试使用单个线程,因为这样可能会造成该线程死锁。如果某个线程正从连接的管道输入流中读取数据字节,但该线程不再处于活动状态,则该管道被视为处于 毁坏 状态。
练习代码:
class AThread extends Thread{
private PipedOutputStream out = new PipedOutputStream();
public PipedOutputStream getOut(){
return this.out;
}
@Override
public void run() {
try {
for(int i = 65 ;i < 65 + 26; i++){
out.write(i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class BThread extends Thread{
private PipedInputStream in = null;
public BThread(AThread aThread) throws Exception{
in = new PipedInputStream(aThread.getOut());
}
@Override
public void run() {
int len = -1;
try {
while ((len = in.read()) != -1){
System.out.println((char)len);
}
in.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
@Test
public void t() throws Exception {
AThread aThread = new AThread();
BThread bThread = new BThread(aThread);
aThread.start();
bThread.start();
}
输出(结果每次运行都不相同):
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z