package com.bjsxt.thread0918;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import com.bjsxt.util.MyUtil;
/**
* 两个线程之间使用 管道流进行信息的收发
* @author yhl
*
*/
public class PipedStreamTest {
public static void main(String[] args) throws Exception{
PipedOutputStream pos = new PipedOutputStream();
//两个流对象建立关联
PipedInputStream pis = new PipedInputStream(pos);
// pos.connect(pis);
PipedOutputStreamThread post = new PipedOutputStreamThread(pos);
PipedInputStreamThread pist = new PipedInputStreamThread(pis);
pist.start();
MyUtil.sleep(5000);
post.start();
}
}
//发送消息的线程
class PipedOutputStreamThread extends Thread{
//持有管道输出流的引用,
private PipedOutputStream pos;
public PipedOutputStreamThread(PipedOutputStream pos) {
super();
this.pos = pos;
}
private void send0() throws IOException{
String str = "我是一个纯粹的唯物主义者,但是关于你,我希望有来生!";
byte[] buf = str.getBytes();
pos.write(buf);
}
//通过键盘输入
private void send1()throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(pos));
String str = br.readLine();
while(true){
bw.write(str);
bw.newLine();
//如果希望对方立即接收数据,那么需要 刷新
bw.flush();
if("bye".equals(str)){
break;
}
str = br.readLine();
}
}
public void run() {
try {
// send0();
send1();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(pos != null){
try {
pos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//接收信息的线程
class PipedInputStreamThread extends Thread{
private PipedInputStream pis;
public PipedInputStreamThread(PipedInputStream pis) {
super();
this.pis = pis;
}
private void receive0() throws IOException{
byte[] buf = new byte[100];
System.out.println("准备接收信息");
// 读取管道输出流写出的信息,如果没有,等待。
int len = pis.read(buf);
System.out.println("接收信息结束");
String recStr = new String(buf,0,len);
System.out.println("接收到的信息:"+recStr);
}
private void receive1() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(pis));
String recStr = br.readLine();
while(true){
System.out.println("接收到的信息:"+recStr);
if("bye".equals(recStr))
break;
recStr = br.readLine();
}
}
public void run() {
try {
receive1();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(pis != null){
try {
pis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}