------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
管道流可以实现两个线程之间,二进制数据的传输。
管道流就像一条管道,一端输入数据,别一端则输出数据。通常要分别用两个不同的线程来控制它们。
使用方法如下:
1.
package twenty_one;
import java.io.*;
public class Two {
public static void main(String[] args)throws IOException {
PipedInputStream in=new PipedInputStream ();
PipedOutputStream out =new PipedOutputStream ();
in.connect(out);
Read r=new Read(in);
Write w=new Write(out);
new Thread(r).start();
new Thread(w).start();
}
}
class Read implements Runnable
{
private PipedInputStream in;
Read(PipedInputStream i)
{
this.in=in;
}
public void run()
{
try
{
byte[]buf=new byte[1024];
System.out.println("读取前..没有数据堵塞");
int len=in.read(buf);
System.out.println("读到数据..堵塞结束");
String s=new String(buf,0,len);
System.out.println(s);
in.close();
}
catch(IOException e)
{
throw new RuntimeException("管道流读取失败");
}
}
}
class Write implements Runnable
{
private PipedOutputStream out;
Write(PipedOutputStream out)
{
this.out=out;
}
public void run()
{
try
{
System.out.println("开始写入数据等待六秒后");
Thread.sleep(6000);//sleep释放执行权。
out.write("pipe lai la".getBytes());
out.close();
}
catch(Exception e)//
{
throw new RuntimeException("管道流输出失败");
}
}
}
2.