我打算使用多线程获得从1到10000000的求和,
下面的代码在这一行中无法正常工作 - sum = sum + Sum(finalI, FinalI * step);
,当前线程中的总和始终为 0。我已经添加了 volatile
,我是java新手,我不知道如何解决这个问题。
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class testParallelFor {
volatile static long sum = 0;
final static int step = 100;
final static int start = 1;
final static int end = 10000000;
public static void main(String[] args) throws InterruptedException {
int num = Runtime.getRuntime().availableProcessors();
ExecutorService exec = Executors.newFixedThreadPool(num);
try {
for (int i = start; i < end; i = i * step) {
int finalI = i;
exec.submit(new Runnable() {
@Override
public void run() {
sum = sum + Sum(finalI, finalI * step);
}
});
}
} finally {
exec.shutdown();
exec.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
sum = sum + end;
System.out.println(sum);
}
}
static long Sum(int i, int j) {
System.out.println("Sum from " + i + " to " + j + " start.");
long temp = 0;
for (int k = i; k < j; k++) {
temp = temp + k;
}
System.out.println("Sum from " + i + " to " + j + " end. sum=" + temp);
return temp;
}
}
输出:
Sum from 1 to 100 start.
Sum from 1000000 to 100000000 start.
Sum from 100 to 10000 start.
Sum from 10000 to 1000000 start.
Sum from 1 to 100 end. sum=4950
Sum from 100 to 10000 end. sum=49990050
Sum from 10000 to 1000000 end. sum=499949505000
Sum from 1000000 to 100000000 end. sum=4999499950500000
4999499960500000
最佳答案
最简单的解决方案可能是使用并行流:
long start = 1;
long end = 10000000;
long result = LongStream.rangeClosed(start, end) // Creates a stream going from 1 to 10000000
.parallel() // Parallelize this stream
.sum(); // Sums every value of this stream
System.out.println(result);
这比你的版本清楚得多:)
关于java - java多线程求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59660413/