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("管道流输出失败");
}
}
}
这段代码显示错误为:
Exception in thread "Thread-0" 读取前..没有数据堵塞
java.lang.NullPointerException
at twenty_one.Read.run(Two.java:27)
at java.lang.Thread.run(Thread.java:662)
开始写入数据等待六秒后
该怎么解决啊?
|
|