java习题 chp12_15 *(多线程)完成下列程序要求有个Student 类,代码如下:
15. **(多线程)完成下列程序要求有个Student 类,代码如下:
class Student{
String name;
int age;
//构造方法和get/set 方法请自行补充完成„
//学生问老师问题
public void ask(Teacher t){
t.answer(this);//调用老师的answer 方法
}
public void study(){
System.out.println(name + “study”);
}
public void doHomework(){
System.out.println(name + “do homework”);
}
}
定义Teacher 接口
interface Teacher{
void answer(Student stu);
}
给出一个Teacher 接口的实现类。该实现类实现answer 方法的时候,要求每次学生调用老师的answer 方法时,都创建一个新线程,该线程调用学生的学习方法和做作业方法。
Student.java
package chp12_15;
public class Student {
String name;
int age;
//构造方法
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
//get|set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//学生问老师问题
public void ask(Teacher t){
t.answer(this);
}
public void study(){
System.out.println(name+" study");
}
public void doHomework(){
System.out.println(name+" do homework");
}
}
Teacher.java
package chp12_15;
public interface Teacher {
void answer(Student stu);
}
TeacherImpl.java
package chp12_15;
public class TeacherImpl implements Teacher{
MyThread mythread ;
public TeacherImpl() {
super();
}
@Override
public void answer(Student stu) {
// TODO Auto-generated method stub
mythread = new MyThread(stu);
mythread.start();
}
}
MyThread.java
package chp12_15;
public class MyThread extends Thread{
private Student student;
public MyThread(Student student) {
// TODO Auto-generated constructor stub
this.student=student;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
student.study();
student.doHomework();
}
}
Test.java
package chp12_15;
public class Test {
public static void main(String[] args) {
Teacher t = new TeacherImpl();
Student s = new Student("abc",20);
s.ask(t);
}
}

浙公网安备 33010602011771号