用java语言2.设计程序模拟上课情景,要求有3个线程,即student1、student2和teacher。其中student1准 备睡觉10分钟后开始上课;其中student2也准备睡觉10分钟后开始上课;teacher在说了一句 “上课!”后吵醒休眠的线程student1,又说了一句“上课!”后吵醒休眠的线程student2。
时间: 2024-01-04 17:10:13 浏览: 29
好的,我可以帮您解答这个问题。下面是参考代码:
```java
public class ClassSimulation {
public static void main(String[] args) {
Student student1 = new Student("Student1", 10);
Student student2 = new Student("Student2", 10);
Teacher teacher = new Teacher();
student1.start();
student2.start();
teacher.start();
}
}
class Student extends Thread {
private int sleepTime;
public Student(String name, int sleepTime) {
super(name);
this.sleepTime = sleepTime;
}
@Override
public void run() {
try {
System.out.println(getName() + " is sleeping...");
Thread.sleep(sleepTime * 1000);
System.out.println(getName() + " wakes up and gets ready for class.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Teacher extends Thread {
@Override
public void run() {
try {
System.out.println("Teacher: \"Class is starting!\"");
Thread.sleep(1000);
System.out.println("Teacher: \"Class is starting!\"");
synchronized (this) {
notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
在这个程序中,我们创建了三个线程:两个学生线程和一个老师线程。每个学生线程都有一个睡眠时间,即在上课之前需要休眠的时间。老师线程负责唤醒两个学生线程。当老师线程启动时,它会打印一句“Class is starting!”,然后等待1秒钟后再打印一遍。接着,老师线程使用`synchronized`关键字将自己的锁定,并使用`notifyAll()`方法唤醒所有等待该锁定的线程,即唤醒两个学生线程。当学生线程被唤醒后,它们会打印一句话,表示它们已经准备好上课了。
希望这个代码能够帮助您理解如何使用Java语言模拟上课情景。如果您还有其他问题,请随时问我。