/*
* 管道流,
* 管道流也分为字节流(PipedOutputStream,PipedInputStream)和字符流(PipedReader,PipedWriter)
* 本例采用字节流
*/
package Test2;
import java.io.*;
public class Demo_23_6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo_23_6 d = new Demo_23_6();
}
public Demo_23_6()
{
//创建线程对象Sender
Sender sender = new Sender();
//创建线程对象Receiver
Receiver receiver = new Receiver();
PipedOutputStream out = sender.get();
PipedInputStream in = receiver.get();
try {
//将输出发送到输入
//将两个管道连接起来
out.connect(in);
//启动线程
new Thread(sender).start();
new Thread(receiver).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Sender implements Runnable
{
private PipedOutputStream out = new PipedOutputStream();
public PipedOutputStream get()
{
return out;
}
@Override
public void run() {
// TODO Auto-generated method stub
String str = new String("Receiver 您好");
try {
//注意把字符流转化为字节流
//写入要发送到的信息
out.write(str.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Receiver implements Runnable
{
private PipedInputStream in = new PipedInputStream();
public PipedInputStream get()
{
return in;
}
@Override
public void run() {
// TODO Auto-generated method stub
String s = null;
/*
* 注意这里的1024,类PipedInputStream运用的是一个1024字节固定大小的循环缓冲区,
* 特别注意上面一句话,大小固定
* 如果当前缓冲区已经被占满,再试图写入的时候,该线程就会被阻塞,直到出现读取PipedInputStream的操作从缓冲区中删除数据
*/
byte[] a = new byte[1024];
try {
//读出数据
int len = in.read(a);
s = new String(a,0,len);
System.out.println("收到了以下信息 : " + s);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Java管道流
最新推荐文章于 2024-08-23 21:03:35 发布