我的任务是创建一个程序,其中 3 名协调员将 200 名学生添加到 1 门课程。我正在使用一个线程池,最后打印已注册该课程的学生编号数组。出于某种原因——在大多数情况下,当我运行 java 主程序时,它确实会向数组中添加 200 名学生——但是!它时不时地分配更少,并告诉我数组大小是 160、170 ...拜托,如果你能看到是什么原因造成的,我希望得到一些帮助。import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ClassMain{ public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(3); for (int i = 1; i <= 200 ;i++) { Runnable coordinator = new Coordinator(i); executor.execute(coordinator); } executor.shutdown(); while (!executor.isTerminated()); Coordinator.print(); }}import java.util.ArrayList;public class Coordinator implements Runnable{ public static ArrayList<Integer> javaStudents; private int studentNumber; public Coordinator(int studentNum) { studentNumber = studentNum; javaStudents = new ArrayList<Integer>(); } public static synchronized void processCommand(int studentNumber) { javaStudents.add(studentNumber); } @Override public void run() { System.out.println(Thread.currentThread().getName() + " Starting to add student# " + studentNumber + " to Java"); processCommand(studentNumber); System.out.println(Thread.currentThread().getName() +" Ended adding student#" + studentNumber + " to Java"); } public static void print() { for (int i = 0; i < javaStudents.size(); i++) { System.out.println("Student #" +javaStudents.get(i) + " enrolled to Java"); } System.out.println("Array size: " + javaStudents.size()); }}我希望数组大小始终为 200,但在某些运行中它会有所不同......
1 回答
达令说
TA贡献1821条经验 获得超6个赞
构造函数中的这一行Coordinator
是问题所在:
javaStudents = new ArrayList<Integer>()
static
javaStudents
每次Coordinator
构造a 时,您都会覆盖该字段。删除此行,并将您的static
字段声明更改为:
public static ArrayList<Integer> javaStudents = new ArrayList<>();
添加回答
举报
0/150
提交
取消