初学java,下面是用多线程精神病医生的例子,(即两个线程对话,你一句,我一句...)程序编译,运行时没有反应,考虑了一下觉得是没有给管道种子,敢问要如何解决阿!import java.io.*;
public class Doctor extends Thread
{
String name;
InputStream in;
OutputStream out;
Doctor(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);
Doctor dr1=new Doctor("Doctor1",sin1,sout2);
Doctor dr2=new Doctor("Doctor2",sin2,sout1);
dr1.start();
dr2.start();
}
public void run()
{
try
{
talk(in,out);
}
catch(Exception e)
{
}
}
void talk(InputStream in,OutputStream out) throws Exception
{
BufferedReader rd=new BufferedReader(
new InputStreamReader(in));
PrintWriter pw=new PrintWriter(
new OutputStreamWriter(out),true);
pw.println("Hello");
while(true)
{
String question=rd.readLine();
reply(pw,question);
} }
void reply(PrintWriter pw,String question) throws Exception
{
Thread.sleep((int)Math.random()*1000);
pw.println(question);
}
}
public class Doctor extends Thread
{
String name;
InputStream in;
OutputStream out;
Doctor(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);
Doctor dr1=new Doctor("Doctor1",sin1,sout2);
Doctor dr2=new Doctor("Doctor2",sin2,sout1);
dr1.start();
dr2.start();
}
public void run()
{
try
{
talk(in,out);
}
catch(Exception e)
{
}
}
void talk(InputStream in,OutputStream out) throws Exception
{
BufferedReader rd=new BufferedReader(
new InputStreamReader(in));
PrintWriter pw=new PrintWriter(
new OutputStreamWriter(out),true);
pw.println("Hello");
while(true)
{
String question=rd.readLine();
reply(pw,question);
} }
void reply(PrintWriter pw,String question) throws Exception
{
Thread.sleep((int)Math.random()*1000);
pw.println(question);
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货