java 线程间的通信 pipedOutStream 和PipedInputStream 管道流

来源:互联网 发布:热力计算软件 编辑:程序博客网 时间:2024/06/07 03:45
package Test1;
import java.io.*;
import java.util.*;
class Send implements Runnable{//定义管道输出流
private OutputStream pipeoutput;
private String name;
public Send(String name){
this.setPipeinput(name);

public void setPipeinput(String name){
this.name=name;
this.pipeoutput=new PipedOutputStream();
}
public PipedOutputStream getPipeoutput(){
return (PipedOutputStream)this.pipeoutput;
}
public void run(){
try{
this.pipeoutput.write(this.name.getBytes());
}catch(Exception e){
e.printStackTrace();
}
}
}
class Recive implements Runnable{//定义管道输入流
private InputStream pipeinput;
public Recive(){
this.setPipeinput();
}
public void setPipeinput(){
this.pipeinput=new PipedInputStream();
}
public PipedInputStream getPipeOutput(){
return (PipedInputStream)this.pipeinput;
}
public void run(){
byte b[]=new byte[1024];
int len=0;
try{
   len=this.pipeinput.read(b);
}catch(IOException e){
e.printStackTrace();
}finally{
System.out.println(new String(b,0,len));
}
}

}
public class PipedDemo01 {//java线程间的通信


/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Send s=new Send("磊哥无敌");
Recive re=new Recive();
Thread S=new Thread(s);
Thread r=new Thread(re);
S.start();
r.start();
re.getPipeOutput().connect(s.getPipeoutput());


}


}
0 0
原创粉丝点击