1
我正在寫一個小型並行程序來計算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)
將calculateMember的代碼包裝在try-catch中並打印所有異常。 –
不是問題,但你應該使用['awaitTermination'](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination-long-java。 util.concurrent.TimeUnit-)而不是'isTerminated'上的忙碌循環 –