printstream对象:
printstream printstream = new printstream(pipeout);
现在,程序可以创建将数据从x改变到y的线程,该线程是ythread类的一个对象,他传递两个参数:输入文件(xfileln)和输出管道(调用printstream)
ythread ythread =new thread(xfileln,printstream);
之后,程序启动线程:
changetoz()方法
changetoz()方法与changetoy()方法很相似,他从changetoy()返回的输入流开始:
datainputstream yfileln= new datainputstream(inputstream);
程序创建一个新的管道:
pipedoutstream pipeout2 = new pipedoutputstream();
pipedinputstream pipeln2 = new pipedinputsream(pipeout2);
该线程通过这个新的管道发出修改后的数据(输入流pipeln2)给主程序。
源程序如下:
//
//pipeapp.Java-pipeapp的主应用程序
//
import Java.io.*
class pipeapp
{
public static void main(string[] args)
{
pipeapp pipeapp=new pipeapp();
try
{
fileinputstream xfile =new fileinputstream("input.txt");
inputstream ylnpipe = pipeapp.changetoy(xfileln);
inputstream zlnpipe=pipeapp.changetoz(ylnpipe);
system.out.println();
system.out.println("here are the results");
system.out.pringln();
datainputstream inputstream = nes datainputstream(zlnpipe);
string str = inputstream.readline();
while (str!=null)
{
system.out.println(str);
str=inputstream.readline();
}
inputstream.close();
}
catch(exception e)
{
system.out.println(e.tostring());
}
}
public inputstream changetoy(inputstream inputstream)
{
try
{
datainputstream pipeout = new datainputsteam(inputstream);
pipedoutstream pipeout = new pipedoutputstream();
pipedlnsteam pipeln = new pipedlnputstream(pipeout);
printstream printstream = new printstream(pipeout);
ythread ythread = new ythread(xfileln,printstream);
ythread.start();
return pipeln;
}
catch(exeption e)
{
system.out.println(x.tostring());
}
return null;
}
public inputstream changetoz(inputstream inputsteam)
{
try
{
datainputstream yfileln = new datainputstream(inputstream);
pipeoutputstream pipeln2 = new pipedinputstream(pipeout2);
printrstream printstream2 = new printsteam(pipeout2);
zthread zthread = new zthread(yfileln,printstream2);
zthread.start();
return pipeln2;
}
catch(exception e)
{
system.out.println(e.tostring());
}
return null;
}
}
Java中利用管道实现线程间的通讯(3)
时间:2007-11-05
Ythread类和Zthread类
由于ythread类与zthread类基本一样,在此仅以ythread为例加以说明。
Ythread的构造器接收两个参数:输入的文件和第一个管道的输出端,构造器存储这两个参数作为类的数据成员:
Ythread(datainputstream xfileln,pringstream printstream)
{
this.xfileln = xfileln;
this.printstream = printstream;
}
线程通过run()方法来处理数据。首先读取一行数据,确保xstring不为空的情况下循环执行:
string xstring = xfileln.readline();
每读一行数据,完成一次转换
string ystring = xstring.replace(''x'',''y'');
然后将修改后的数据输出到管道的输出端:
prinstream.prinrln(ystring);
为了确保所有缓冲区的数据完全进入管道的输出端:
pringstram.flush();
循环完成后,线程关闭管道输出流:
pringstram.close();
ythread类的源程序如下:
//
//ythread.Java
//
import Java.io.*;
class yth
|