java模拟三个老师同时给50个小朋友发苹果,每个老师相当于一个线程,每个小朋友发一个苹果,按照小朋友的顺序有序分发,利用多线程模拟老师发苹果过程。
时间: 2024-03-10 18:43:57 浏览: 68
可以使用Java中的线程池来模拟三个老师的发苹果过程,每个线程负责发苹果给若干个小朋友。以下是实现的代码示例:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AppleTeacher implements Runnable {
private int start;
private int end;
private String name;
public AppleTeacher(int start, int end, String name) {
this.start = start;
this.end = end;
this.name = name;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
System.out.println(name + "老师给第" + i + "个小朋友发苹果");
}
}
public static void main(String[] args) {
int totalStudents = 50;
int studentsPerTeacher = totalStudents / 3;
ExecutorService executorService = Executors.newFixedThreadPool(3);
executorService.submit(new AppleTeacher(1, studentsPerTeacher, "A"));
executorService.submit(new AppleTeacher(studentsPerTeacher + 1, studentsPerTeacher * 2, "B"));
executorService.submit(new AppleTeacher(studentsPerTeacher * 2 + 1, totalStudents, "C"));
executorService.shutdown();
}
}
```
在上面的代码中,我们定义了一个AppleTeacher类实现了Runnable接口,并在其中实现了老师发苹果的逻辑。在主函数中,我们首先计算出每个老师需要发给的小朋友的编号范围,然后创建一个线程池,并将三个老师的任务提交到线程池中。最后,我们调用shutdown()方法关闭线程池。
运行上面的代码,可以看到三个老师依次给50个小朋友发苹果,每个小朋友都按照顺序接收到了一个苹果。
阅读全文