java - java多线程求和

标签 java multithreading

我打算使用多线程获得从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/

相关文章:

Java:jasper报告删除尾随零

java - 使用 DocumentListener 实现检查 JTextField

java - 如何使用java多线程将大文本文件分割成更小的 block

java - ExecutorService 队列中的最大等待时间

java - 使用 HashMap 查找字符串中第二常见的字符

java - Java中如何从数组中删除一个对象?

java - 反序列化由@JsonIdentityInfo 序列化的对象

ruby - 学习Ruby线程-线程完成时触发事件

c++ - 使用 string 和 int(like) 类型初始化模板类的静态成员

c# - Thread.Sleep(TimeSpan) 有多准确?