模拟三个老师同时给十个小朋友发礼品,每个老师相当于一个线程
时间: 2023-07-20 21:33:41 浏览: 201
下面是 Java 代码实现,模拟三个老师同时给十个小朋友发礼品,每个老师相当于一个线程:
```java
public class TeacherThread implements Runnable {
private int teacherID;
public TeacherThread(int teacherID) {
this.teacherID = teacherID;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Teacher " + teacherID + " gives present to student " + i);
try {
Thread.sleep(100); // 模拟发礼品的时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// 创建三个老师的线程
Thread teacher1 = new Thread(new TeacherThread(1));
Thread teacher2 = new Thread(new TeacherThread(2));
Thread teacher3 = new Thread(new TeacherThread(3));
// 启动三个老师的线程
teacher1.start();
teacher2.start();
teacher3.start();
}
}
```
这个例子中,我们使用了 Runnable 接口来实现线程,并且在 run 方法中模拟老师发礼品的过程。通过创建三个 TeacherThread 线程对象分别对应三位老师,并启动这三个线程,我们就可以模拟三个老师同时给十个小朋友发礼品的场景。需要注意的是,在实际应用中,我们需要考虑到线程安全等问题。
阅读全文