首页 > 代码库 > java 管道流PipedOutputStream和PipedInputStream基本操作
java 管道流PipedOutputStream和PipedInputStream基本操作
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();
}
}
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。