7.1 管道流
在Java的JDK中提供了4个类来使线程间可以进行通信PipedInputStream
PipedOutputStream
PipedReader
PipedWriter
7.2 使用案例
write类
public class writer {
public void writeData(PipedOutputStream out)
{
try{
System.out.println("write: ");
for(int i=0;i<300;i++)
{
String outData = "" + (i + 1);
out.write(outData.getBytes());
System.out.println(outData);
Thread.sleep(10);
}
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
reader类
public class reader {
public void readData(PipedInputStream input)
{
try{
System.out.println("read: ");
byte[] byteArr = new byte[20];
int len = input.read(byteArr);
while (len != -1){
String newData = new String(byteArr,0,len);
System.out.println(newData);
len = input.read(byteArr);
}
System.out.println();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
主函数
public class test{
public static void main(String[] args)
{
try {
writer writeData = new writer();
reader readDate = new reader();
PipedOutputStream out = new PipedOutputStream();
PipedInputStream input = new PipedInputStream();
//input.connect(out);
out.connect(input);
new Thread(new Runnable() {
@Override
public void run() {
writeData.writeData(out);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
readDate.readData(input);
}
}).start();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}