输出结果我认为应该是:
Send run!
the message is coming from hello getter
Get run!而实际上是:
the message is coming from hello getter
Get run!
Send run!
import java.io.*;public class PipeStreamTestExample {
public static void main(String args[]) throws Exception {
try {
Send t1 = new Send();
Get t2 = new Get();
t1.getOutputStream().connect(t2.getInputStream());
t1.start();
t2.start();
} catch (IOException e) {
System.out.println(e.getMessage());
} }
}
class Get extends Thread {
private PipedInputStream in = new PipedInputStream();
public PipedInputStream getInputStream() {
return in;
}
public void run() {
String s = null;
byte[] buf = new byte[1024];
try {
int len = in.read(buf);
s = new String(buf,0,len);
System.out.println("the message is coming from " + s);
in.close();
System.out.println("Get run!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
class Send extends Thread {
private PipedOutputStream out = new PipedOutputStream();
public PipedOutputStream getOutputStream() {
return out;
}
public void run() {
String s = new String("hello getter ");
try {
out.write(s.getBytes());
out.close();
System.out.println("Send run!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Send run!
the message is coming from hello getter
Get run!而实际上是:
the message is coming from hello getter
Get run!
Send run!
import java.io.*;public class PipeStreamTestExample {
public static void main(String args[]) throws Exception {
try {
Send t1 = new Send();
Get t2 = new Get();
t1.getOutputStream().connect(t2.getInputStream());
t1.start();
t2.start();
} catch (IOException e) {
System.out.println(e.getMessage());
} }
}
class Get extends Thread {
private PipedInputStream in = new PipedInputStream();
public PipedInputStream getInputStream() {
return in;
}
public void run() {
String s = null;
byte[] buf = new byte[1024];
try {
int len = in.read(buf);
s = new String(buf,0,len);
System.out.println("the message is coming from " + s);
in.close();
System.out.println("Get run!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
class Send extends Thread {
private PipedOutputStream out = new PipedOutputStream();
public PipedOutputStream getOutputStream() {
return out;
}
public void run() {
String s = new String("hello getter ");
try {
out.write(s.getBytes());
out.close();
System.out.println("Send run!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
你的send执行到out.write(s.getBytes());的时候,get开始执行,就能输出the message is coming from hello getter 和Get run!,然后get执行完成,send才获得执行机会,自然就出现了这样的情况。如果你想达到预期的效果,可以加上一些线程的同步机制来完成。