标签:java 管道流 pipedinputstream pipedoutputstream
java的管道流要PipedOutputSream和PipedInputStream结合起来使用,管道流主要用来进行线程之间的通信。
上代码
import java.io.*;
public class PipeStreamDemo
{
public static void main(String[] args)
{
PipedOutputStream out=null;
PipedInputStream in=null;
Sender sender=new Sender();
Receiver receiver=new Receiver();
out=sender.getOutputStream();
in=receiver.getInputStream();
try
{
out.connect(in);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
sender.start();
receiver.start();
}
}
class Sender extends Thread
{
private PipedOutputStream out=new PipedOutputStream();
public PipedOutputStream getOutputStream()
{
return out;
}
public void run()
{
String str="Hello, my name is cjc!";
try
{
out.write(str.getBytes());
out.close();
System.out.println("The sender Thread sends string \""+str+"\".");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Receiver extends Thread
{
private PipedInputStream in=new PipedInputStream();
public PipedInputStream getInputStream()
{
return in;
}
public void run()
{
byte[] b=new byte[1024];
try
{
int num=in.read(b);
in.close();
if(num==-1)
{
System.out.println("The receiver Thread receives nothing!!!");
}
else
{
System.out.println("The receiver Thread receices \""+new String(b,0,num)+"\".");
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
java 管道流PipedOutputStream和PipedInputStream基本操作,布布扣,bubuko.com
java 管道流PipedOutputStream和PipedInputStream基本操作
标签:java 管道流 pipedinputstream pipedoutputstream
原文地址:http://blog.csdn.net/cjc211322/article/details/24887119