我编写了一个使用线程来计算数字pi的程序。不幸的是,我现在遇到的问题是,程序在计算之后以及执行main方法中的所有代码后都不会终止自身。有人可以提示我可能是什么吗?
CalculatePi pi = new Leibniz();
pi.startCalculation(4); //starts four threads
long timeStart = System.currentTimeMillis();
int i = 0;
while(i < MAX_PRECISION) {
someDelay(); // just some sleep() delay
i++;
}
long timeStop = System.currentTimeMillis();
pi.stopCalculation(); //stops all threads
System.out.println((timeStop - timeStart) + " ms");
System.out.println(pi.getValue());
//After this code the program keeps running
编辑:
public void run() {
BigDecimal counter = new BigDecimal("1");
while( !flag ) {
// counter % numThreads == threadRemainder
if(counter.intValue() % numOfAllThreads == numOfThread)
// if counter % 2 == 1 , get all odd numbers
if(counter.remainder(new BigDecimal("2")).equals(BigDecimal.ONE)) {
// calculate this.value = this.value + 1 / (2 * counter + 1)
threadResult = threadResult.add(BigDecimal.ONE.divide(((new BigDecimal("2").multiply(counter).subtract(BigDecimal.ONE))), 1000, RoundingMode.HALF_UP));
}else {
// calculate this.value = this.value - 1 / (2 * counter + 1)
threadResult = threadResult.subtract(BigDecimal.ONE.divide(((new BigDecimal("2").multiply(counter).subtract(BigDecimal.ONE))), 1000, RoundingMode.HALF_UP));
}
// Inkrement counter to check next number
counter = counter.add(new BigDecimal("1"));
}
}
启动线程的方法:
// Multi-Threading
public boolean startCalculation(int numThreads) {
//The executor handles the thread execution
ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
// Set Thread-Array length to numThreads
workers = new LeibnizThread[numThreads];
for (int i = 0; i < numThreads; i++) {
workers[i] = new LeibnizThread(numThreads, i);
// //executorService starts Thread by calling run()
executorService.submit(workers[i]);
}
return true;
}
'
flag'的值在循环中未更改。这使循环无限期地运行。在某种情况下将标志的值更改为'true'将中断while循环,并允许程序按预期终止。
以下是打破循环的例子:
// Example 1: Break the loop after a maximum of 100 iterations. int iteration = 1; while ( !flag ) { // ... // Force the program to terminate after a maximum of 100 iterations. iteration++; if (iteration == 100) { break; } } // Example 2: Break the loop by changing flag when some condition is true. while ( !flag ) { // ... // Change flag on a condition, so that the loop will break. if ( // some condition ) { flag = true; } }