用JAVA写出下面程序,要求:有3个线程,即 studentl、student2 和 teacher。其中 studentl 准备睡10分钟后再开始上课;student2 淮备睡1小时后再开始上课;teacher 在输出 了句“上课!”后砂醒休眠的线程 studentI,studentI 被吵醒后再负 责吵醒休眠的线程 student2。
时间: 2024-01-04 12:09:03 浏览: 86
好的,以下是使用Java实现的代码:
```java
public class Main {
public static void main(String[] args) {
Student student1 = new Student("Student1", 10);
Student student2 = new Student("Student2", 60);
Teacher teacher = new Teacher("Teacher", student1, student2);
teacher.start();
}
}
class Student extends Thread {
private int sleepTime;
public Student(String name, int sleepTime) {
super(name);
this.sleepTime = sleepTime;
}
public void run() {
System.out.println(getName() + " is sleeping for " + sleepTime + " minutes");
try {
Thread.sleep(sleepTime * 60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + " is awake now!");
}
}
class Teacher extends Thread {
private Student student1;
private Student student2;
public Teacher(String name, Student student1, Student student2) {
super(name);
this.student1 = student1;
this.student2 = student2;
}
public void run() {
System.out.println(getName() + " says: Class is starting!");
student1.start();
try {
student1.join();
System.out.println(getName() + " wakes up " + student2.getName());
student2.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + " says: Class is over!");
}
}
```
在这个实现中,我们同样创建了一个`Teacher`线程和两个`Student`线程。与Python实现不同的是,Java中需要继承`Thread`类并重写`run()`方法来创建线程。`Teacher`线程启动`Student1`线程后,调用`join()`方法等待它结束,然后输出一句话并通过`interrupt()`方法中断`Student2`线程的睡眠,让它醒来。注意到在`Student1`的`run()`方法中,我们使用了`Thread.sleep()`方法来让线程睡眠一定的时间,在`Teacher`线程中我们中断了`Student2`线程的睡眠,这都有可能抛出`InterruptedException`异常,因此需要在合适的位置进行异常处理。
阅读全文