谁能告诉我这段代码什么意思?

zhouyonghua0520 2005-03-21 06:11:50
1.精神病医生(一)
(1)一个不断循环的程序,通过System.in读入句子,进行简单的词法分析后,由System.out送出对话回答;
(2)不要求实现复杂的人工智能,只要能输入输出即可.
2.精神病医生(二)
(1)在一的基础上,在学习了多线程后,用两个线程实现自动对话;
(2)线程与线程之间采用PippedStream进行通讯;
(3)对话的过程通过System.out输出.
暂时做成医生听到什么回答什么,怎样触发?也就是让医生说第一句话??
import java.io.*;

public class Doctor extends Thread{
private String name;
private InputStream in;
private OutputStream out;
public 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("Wang", sin1, sout2);
Doctor dr2 = new Doctor("Zhang", sin2, sout1);
dr1.start();
dr2.start();
}
public void run() {
try {
talk(in, out);
} catch (Exception e) {
e.printStackTrace();
}

}
public void talk(InputStream in, OutputStream out) throws Exception {
BufferedReader rd = new BufferedReader(
new InputStreamReader(in));
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(out),true);
String question;
while( true ) {
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);
}
}
...全文
107 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhouyonghua0520 2005-03-27
  • 打赏
  • 举报
回复
自己顶!
Tomcat4 2005-03-22
  • 打赏
  • 举报
回复
zhanghaifei8011 2005-03-21
  • 打赏
  • 举报
回复
演示才能直观的理解代码!
zhouyonghua0520 2005-03-21
  • 打赏
  • 举报
回复
怎么才能够演示??
cuilichen 2005-03-21
  • 打赏
  • 举报
回复
这段代码使用多线程,模拟两个人之间的对话。
主要目的是实现线程之间的通讯。
这段代码没有实现输入,比如使用System.in等
所以没办法演示。
但是,大体的框架是对的。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧