如何确保线程被完全执行? (使用线程池)

时间:2019-06-04 19:03:58

标签: java arrays threadpool

我的任务是创建一个程序,其中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());
    }
}

我希望Array的大小始终为200,但在某些情况下会有所不同...

1 个答案:

答案 0 :(得分:2)

您的Coordinator构造函数中的这一行是问题所在:

javaStudents = new ArrayList<Integer>()

每次构造static时,您将覆盖javaStudents Coordinator字段。删除此行,然后将您的static字段声明更改为:

public static ArrayList<Integer> javaStudents = new ArrayList<>();