java中输入输出的总括——管道流

不想把别人的东西占为己有,但是想方便日后参考还是摘录了。

烦死了,看Java编程思想三或者四,感觉老外写书跟我们看书的习惯都不一样的,总感觉老外写的东西就像是在写手册,全面但是烦琐。

【原则】不要告诉我历史,告诉我怎么做就行了。

【事实】输出输入类,就是TMD的简单,为什么非要弄成手册,让我这个菜鸟看不懂

【鸣谢】中国IT实验室的总结篇

 ——————————————————————————————————————————————————————————

管道流

管道用来把一个程序、线程和代码块的输出连接到另一个程序、线程和代码块的输入。java.io中提供了类PipedInputStream和PipedOutputStream作为管道的输入/输出流
管道输入流作为一个通信管道的接收端,管道输出流则作为发送端。管道流必须是输入输出并用,即在使用管道前,两者必须进行连接
管道输入/输出流可以用两种方式进行连接:
–     在构造方法中进行连接
•     PipedInputStream(PipedOutputStream pos);
•     PipedOutputStream(PipedInputStream pis);
–     通过各自的connect()方法连接
•     在类PipedInputStream中,connect(PipedOutputStream pos);
    
•     在类PipedOutputStream中,connect(PipedInputStream pis);
例 8.8 管道流。
本例例管道流的使用方法。设输入管道in与输出管道out已连接,Send线程向输出管道out发送数据,Receive线程从输入管道in中接收数据。程序如下:
import java.io.*;
public class Pipedstream
{
public static void main (String args[])
{
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
try
{
in.connect(out);
}
catch(IOException ioe) { }
Send s1 = new Send(out,1);
Send s2 = new Send(out,2);
Receive r1 = new Receive(in);
Receive r2 = new Receive(in);
s1.start();
s2.start();
r1.start();
r2.start();
}
}
class Send extends Thread //发送线程
{
PipedOutputStream out;
static int count=0; //记录线程个数
int k=0;
public Send(PipedOutputStream out,int k)
{
this.out= out;
this.k= k;
this.count++; //线程个数加1
}
public void run( )
{
System.out.print("/r/nSend"+this.k+": "+this.getName()+" ");
int i=k;
try
{
while (i<10)
{
out.write(i);
i+=2;
sleep(1);
}
if (Send.count==1) //只剩一个线程时
{
out.close(); //关闭输入管道流
System.out.println(" out closed!");
}
else
this.count--; //线程个数减1
}
catch(InterruptedException e) { }
catch(IOException e) { }
}
}
class Receive extends Thread //接收线程
{
PipedInputStream in;
public Receive(PipedInputStream in)
{
this.in = in;
}
public void run( )
{
System.out.print("/r/nReceive: "+this.getName()+" ");
try
{
int i = in.read();
while (i!=-1) //输入流未结束时
{
System.out.print(i+" ");
i = in.read();
sleep(1);
}
in.close(); //关闭输入管道流
}
catch(InterruptedException e) { }
catch(IOException e)
{
System.out.println(e);
}
}
}
程序运行结果如下:
Send1: Thread-0
Send2: Thread-1
Receive: Thread-2 1
Receive: Thread-3 2 3 4 5 7 out closed!
6 8 9 java.io.IOException: Pipe closed!

 


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/willsxp/archive/2008/04/19/2306044.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值