import java.io.*;public class PipeStreamTest {
public static void main(String[] args)
{
try{
Thread t1=new Sender();
Thread t2=new Receiver();
PipedOutputStream out=t1.getOutputStream();
PipedOutputStream in=t2.getInputStream();
out.connect(in);
t1.start();
t2.start();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
class Sender extends Thread
{
private PipedOutputStream out=new PipedOutputStream();
public PipedOutputStream getOutputStream()
{
return out;
}
public void run()
{
String s=new String("Hello,receiver ,how are you.");
try
{
out.write(s.getBytes());
out.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
class Receiver extends Thread
{
private PipedInputStream in=new PipedInputStream();
public PipedInputStream getInputStream()
{
return in;
}
public void run()
{
String s=null;
byte[] buff=new byte[1024];
try
{
int len=in.read(buff);
s=new String(buff,1,len);
System.out.println("the following message comes from sender:\n"+s);
in.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
这是《java就业培训教程》上的例子 我怎么编译通不过啊 ~~~~
public static void main(String[] args)
{
try{
Thread t1=new Sender();
Thread t2=new Receiver();
PipedOutputStream out=t1.getOutputStream();
PipedOutputStream in=t2.getInputStream();
out.connect(in);
t1.start();
t2.start();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
class Sender extends Thread
{
private PipedOutputStream out=new PipedOutputStream();
public PipedOutputStream getOutputStream()
{
return out;
}
public void run()
{
String s=new String("Hello,receiver ,how are you.");
try
{
out.write(s.getBytes());
out.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
class Receiver extends Thread
{
private PipedInputStream in=new PipedInputStream();
public PipedInputStream getInputStream()
{
return in;
}
public void run()
{
String s=null;
byte[] buff=new byte[1024];
try
{
int len=in.read(buff);
s=new String(buff,1,len);
System.out.println("the following message comes from sender:\n"+s);
in.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
这是《java就业培训教程》上的例子 我怎么编译通不过啊 ~~~~
Thread t2=new Receiver();
PipedOutputStream out=t1.getOutputStream();
PipedOutputStream in=t2.getInputStream();
out.connect(in);
t1.start();
t2.start();
做一下强制转换:(thread类里显然没有getOutputStream()方法,需要强制转换。) Thread t1=new Sender();
Thread t2=new Receiver(); PipedOutputStream out=((Sender)t1).getOutputStream(); //需要转换。
PipedInputStream in=((Receiver)t2).getInputStream(); //需要转换。
out.connect(in);
t1.start();
t2.start();