1.以下程序模拟上课过程,有两个线程:student和teacher,其中student准备睡一小时后再开始上课,teacher在输出3句“上课”后,吵醒休眠的线程student。将程序补充完整。(15分) class ClassRoom implements Runnable { Thread student,teacher; ClassRoom() { teacher=new Thread(this); _______(1)______ //创建student线程 teacher.setName("王教授"); student.setName("张三"); } public void run(){ if(Thread.currentThread()==student) { try{ System.out.println(student.getName()+"正在睡觉,不听课"); Thread.sleep(1000*60*60); } catch(InterruptedException e) { System.out.println(student.getName()+"被老师叫醒了"); } System.out.println(student.getName()+"开始听课"); } else if(_____(2)______) { for(int i=1;i<=3;i++) { System.out.println("上课!"); try{ Thread.sleep(500); } catch(InterruptedException e){} } student.interrupt(); //吵醒student } } } public class Example { public static void main(String args[]) { ClassRoom room6501=new ClassRoom(); room6501.student.start(); _______(3)_________ //开启teacher线程 } }
时间: 2024-02-14 10:09:07 浏览: 80
补充完整的程序如下:
```
class ClassRoom implements Runnable {
Thread student, teacher;
ClassRoom() {
teacher = new Thread(this);
student = new Thread(this); //创建student线程
teacher.setName("王教授");
student.setName("张三");
}
public void run() {
if (Thread.currentThread() == student) {
try {
System.out.println(student.getName() + "正在睡觉,不听课");
Thread.sleep(1000 * 60 * 60);
} catch (InterruptedException e) {
System.out.println(student.getName() + "被老师叫醒了");
}
System.out.println(student.getName() + "开始听课");
} else if (Thread.currentThread() == teacher) {
for (int i = 1; i <= 3; i++) {
System.out.println("上课!");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
student.interrupt(); //吵醒student
}
}
}
public class Example {
public static void main(String args[]) {
ClassRoom room6501 = new ClassRoom();
room6501.student.start();
Thread.sleep(1000 * 60 * 60); //等待1小时
room6501.teacher.start(); //开启teacher线程
}
}
```
解释如下:
1. 在ClassRoom类的构造方法中,先创建了teacher线程,然后创建了student线程,并为它们设置了名称。
2. 在run方法中,如果当前线程是student线程,那么它先休眠1小时,然后输出“张三开始听课”。
3. 如果当前线程是teacher线程,那么它输出3次“上课!”,每次输出后休眠500毫秒,然后调用student.interrupt()方法,将student线程从休眠状态中唤醒。
4. 在main方法中,先创建了一个ClassRoom对象room6501,然后启动student线程,并让主线程休眠1小时(因为student线程要睡1小时),最后启动teacher线程。这样就能实现teacher线程在student线程睡觉后将其唤醒,让它开始听课了。
阅读全文