为什么当所有任务都执行完后我总是得到空值

Why do I keep getting null values when all tasks have finished execution

我正在编写一个小型并行程序来计算 e 的值。如果线程池中的所有任务都已完成,我不明白为什么数组中的某些值为空。欢迎任何有关澄清问题所在的帮助。代码如下:

import java.math.BigDecimal;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class main {

private static BigDecimal [] taylorSeriesMemebers;

public static void main(String[] args) {

    int seriesSize = 20;
    int threadCount = 6;

    taylorSeriesMemebers = new BigDecimal[seriesSize];

    ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);

    for(int i = 0 ; i < seriesSize ; i++) {
        int k = i;
        threadPool.submit(() -> {
            calculateMember(k);             
        });
    }

    threadPool.shutdown();

    while(!threadPool.isTerminated()) {

    }

    System.out.println("All tasks finished");

    BigDecimal answer = BigDecimal.ZERO;
    for(BigDecimal bd : taylorSeriesMemebers) {
        answer = answer.add(bd);
    }

    System.out.println(answer.toString());
}


private static void calculateMember(int k) {

    BigDecimal first = new BigDecimal(k*2 + 1);

    BigDecimal second = bigFactoriel(2*k);


    BigDecimal divided = first.divide(second);
    taylorSeriesMemebers[k] = divided;


}

private static BigDecimal bigFactoriel(int k) {

    BigDecimal factNumber = BigDecimal.ONE;
    if ( k < 2 ) {
        return factNumber;
    }
    for(int i = 2; i <= k; i++) {
        factNumber = factNumber.multiply(new BigDecimal(i));
    }
    return factNumber;

}

}

异常

All tasks finished
Exception in thread "main" java.lang.NullPointerException
at java.math.BigDecimal.add(Unknown Source) // <-- in the for loop
at test.main.main(main.java:37)

问题是divide的调用,你要改成:

BigDecimal divided = first.divide(second, MathContext.DECIMAL128);

确实出现了ArithmeticException: “Non-terminating decimal expansion; no exact representable decimal result”