java的管道流,两个线程,输出流输出数据,输入流就是不读取
代码如下:
import java.io.*;
public class TestPipeIoStream
{
public static void main( String[] args ) throws Exception
{
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
pis.connect(pos);
ThreadSend ts = new ThreadSend(pos);
ThreadRecv tr = new ThreadRecv(pis);
new Thread(ts).run();
new Thread(tr).run();
}
}
class ThreadSend implements Runnable
{
PipedOutputStream pos;
FileInputStream fis ;
ThreadSend( PipedOutputStream p )
{
pos = p;
}
public void run()
{
try
{
System.out.println("len=");
fis = new FileInputStream("TestPipeIoStream.java");
byte[] buf = new byte[100];
int len;
while( (len=fis.read(buf)) >0 )
{
System.out.println("len="+len);
pos.write( buf );
pos.flush();
//System.out.printf(new String(buf,0,len));
}
pos.close();
fis.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
class ThreadRecv implements Runnable
{
PipedInputStream pis;
ThreadRecv( PipedInputStream p )
{
pis = p;
}
public void run()
{
try
{
byte[] buf = new byte[100];
int len=0;
while( ( len = pis.read(buf) ) >0 )
{
System.out.println("recv len="+len);
System.out.println(new String(buf,0,len));
}
pis.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
------解决方案--------------------
new Thread(ts).run();
new Thread(tr).run();
修改成
new Thread(ts).start();
new Thread(tr).start();
run();应该是没有开新的线程, start方法才是创建了新的线程。
代码中没有创建新的线程,是串行执行的。