已知某学校有n名教师,学校有m名学生,学校搞学生民意调查,每一位学生为每一位老师都打分,学生所打的所有的分数都集中到一个数组中。数据存放规律是,前m个数据是对1号老师的打分,接下来m个数据是对2号老师的打分,以此类推。请设计一个多线程的算法,计算出每一位老师的总打分。java代码
时间: 2024-04-05 19:31:44 浏览: 172
程序用JAVA编写,统计每个学生的总分
以下是一个可能的多线程算法,使用线程池来管理线程:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TeacherRating {
private int[] ratings;
private int numTeachers;
private int numStudents;
public TeacherRating(int[] ratings, int numTeachers, int numStudents) {
this.ratings = ratings;
this.numTeachers = numTeachers;
this.numStudents = numStudents;
}
public int[] calculateTotalRatings() {
ExecutorService executor = Executors.newFixedThreadPool(numTeachers);
int[] totalRatings = new int[numTeachers];
for (int i = 0; i < numTeachers; i++) {
final int teacherIndex = i;
executor.execute(new Runnable() {
@Override
public void run() {
int total = 0;
for (int j = teacherIndex * numStudents; j < (teacherIndex + 1) * numStudents; j++) {
total += ratings[j];
}
totalRatings[teacherIndex] = total;
}
});
}
executor.shutdown();
while (!executor.isTerminated()) {}
return totalRatings;
}
public static void main(String[] args) {
int[] ratings = {3, 4, 5, 2, 1, 3, 2, 5, 4, 1, 3, 2, 4, 5, 1, 2};
int numTeachers = 4;
int numStudents = ratings.length / numTeachers;
TeacherRating teacherRating = new TeacherRating(ratings, numTeachers, numStudents);
int[] totalRatings = teacherRating.calculateTotalRatings();
for (int i = 0; i < numTeachers; i++) {
System.out.println("Teacher " + (i + 1) + " total rating: " + totalRatings[i]);
}
}
}
```
算法将每个老师的计算任务分配给一个线程来完成。使用线程池可以方便地管理线程。在主线程中等待所有线程完成后,算法返回每个老师的总打分。
阅读全文