为什么在所有任务完成执行后我都会继续获取空值

时间:2016-06-25 17:32:07

标签: java parallel-processing executorservice bigdecimal

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

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)

1 个答案:

答案 0 :(得分:3)

问题在于divide的调用,您必须将其更改为:

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

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