实现两个神经病医生对话。。
这是(翁恺)JAVA语言第23讲里讲的一个题目,他一步一步做,还没做完,下课了。。
结果留下来这个运行了没反应的程序
我觉的这程序别扭,但是找不出哪里出错了
贴出来给大家看看
import java.io.*;
public class Doctor2 extends Thread {
private String name;
private InputStream in;
private OutputStream out;
Doctor2(String name, InputStream in, OutputStream out){
this.name = name;
this.in = in;
this.out = out;
}
public static void main(String[] args) throws Exception {
PipedInputStream sin1 = new PipedInputStream();
PipedOutputStream sout1 = new PipedOutputStream(sin1);
PipedInputStream sin2 = new PipedInputStream();
PipedOutputStream sout2 = new PipedOutputStream(sin2);
Doctor2 dr1 = new Doctor2( "Wang ",sin1,sout2);
Doctor2 dr2 = new Doctor2( "Zhang ",sin2,sout1);
dr1.start();
dr2.start();
}
public void run() {
try{
talk(in,out);
}catch(Exception e){
}
}
public void talk(InputStream in , OutputStream out) throws Exception{
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out,true);
pw.println(name+ "Hello ");
while(true){
String question = rd.readLine();
reply(pw,question);
}
}
private void reply(PrintWriter out,String question) throws Exception {
Thread.sleep((int)Math.random()*1000);
out.println(name+ ": "+question);
}
}
------解决方案--------------------
学习。。。
------解决方案--------------------
这个程序我看着没有问题啊,不过这个程序有点不好,一个是在里面用了个死循环。while(true),这样下去不会结束。
另外一个就是我认为main函数应该独立出来在另一个类中。