import java.io.*;
//用管道流实现线程间的通信
class SendMessage implements Runnable
{
private PipedOutputStream out;
public SendMessage()
{
out=new PipedOutputStream();
}
public PipedOutputStream getOut()
{
return this.out;
}
public void run()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=null;
try
{ System.out.println("请输入信息,按回车键结束:");
str = br.readLine();
}
catch (IOException e1)
{
e1.printStackTrace();
}
try
{
out.write(str.getBytes());
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("发送的内容:"+str);
}
}
class RectMessage implements Runnable
{
private PipedInputStream in;
public RectMessage()
{
in=new PipedInputStream();
}
public PipedInputStream getIn()
{
return this.in;
}
public void run()
{
byte b[]=new byte[1024];
int len=0;
try
{
len=in.read(b);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("收到的内容是:"+new String(b,0,len));
}
}
public class Demo9 {
public static void main(String[] args)
{
SendMessage sm=new SendMessage();
RectMessage rm=new RectMessage();
Thread t1=new Thread(sm);
Thread t2=new Thread(rm);
PipedOutputStream os=sm.getOut();
PipedInputStream is=rm.getIn();
try
{
os.connect(is);//将输出连接到输入
}
catch (IOException e)
{
e.printStackTrace();
}
t1.start();
t2.start();
}
}
//用管道流实现线程间的通信
class SendMessage implements Runnable
{
private PipedOutputStream out;
public SendMessage()
{
out=new PipedOutputStream();
}
public PipedOutputStream getOut()
{
return this.out;
}
public void run()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=null;
try
{ System.out.println("请输入信息,按回车键结束:");
str = br.readLine();
}
catch (IOException e1)
{
e1.printStackTrace();
}
try
{
out.write(str.getBytes());
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("发送的内容:"+str);
}
}
class RectMessage implements Runnable
{
private PipedInputStream in;
public RectMessage()
{
in=new PipedInputStream();
}
public PipedInputStream getIn()
{
return this.in;
}
public void run()
{
byte b[]=new byte[1024];
int len=0;
try
{
len=in.read(b);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("收到的内容是:"+new String(b,0,len));
}
}
public class Demo9 {
public static void main(String[] args)
{
SendMessage sm=new SendMessage();
RectMessage rm=new RectMessage();
Thread t1=new Thread(sm);
Thread t2=new Thread(rm);
PipedOutputStream os=sm.getOut();
PipedInputStream is=rm.getIn();
try
{
os.connect(is);//将输出连接到输入
}
catch (IOException e)
{
e.printStackTrace();
}
t1.start();
t2.start();
}
}