gpt4 book ai didi

java - ExecutorService 池中的数组中所有元素的总和不起作用

转载 作者:行者123 更新时间:2023-12-01 21:40:03 27 4
gpt4 key购买 nike

我试图理解 ExecutorService 并且我想对数组的所有元素求和。我做了两种方法,一种是连续求和(只是一个对所有元素求和的 for 循环),另一种是与池同时求和。我的问题是,使用 ExecutorService 的总和几乎总是与序列总和不一致,有时甚至只有 1。

package sumArregloConc;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class SumaArregloMain {

private final static int cantElem = 1000;
private static ExecutorService tpool = Executors.newCachedThreadPool();



public static void main(String[] args)
{

int[] arreglo = generarArreglo(cantElem); //generate the array with random numbers

System.out.println(sumaSerial(arreglo));
System.out.println(sumaConcurrente(arreglo));
}

public static int sumaSerial(int[] arreglo)
{
int suma = 0;
for(int i =0; i< arreglo.length; i++)
{
suma += arreglo[i];
}

return suma;

}

public static int sumaConcurrente(int[] arreglo)
{
AtomicInteger total = new AtomicInteger(0);

for(int i = 1 ; i < cantElem; i++){

int a = arreglo[i];
Thread thread = new Thread(new Runnable(){
public void run() {
int res = a;
total.addAndGet(res);
return;
}});
tpool.submit(thread);
}

tpool.shutdown(); //wait for everything to finish
return total.get();
}

public static int[] generarArreglo(int cantElem)
{
int[] arreglo = new int[cantElem];
Random rand = new Random();

for(int i = 0; i < cantElem; i++)
{
arreglo[i] = rand.nextInt(10);
}

return arreglo;
}
}

谁能告诉我出了什么问题吗?

最佳答案

发现错误。首先,Eric 谈到了awaitTermination 和Runnable,但主要的错误是循环从i = 1 而不是i = 0 开始,愚蠢的错误。

    public static int sumaConcurrente(int[] arreglo)
{
AtomicInteger total = new AtomicInteger(0);

for(int i = 0 ; i < cantElem; i++){

int a = arreglo[i];

tpool.submit(new Runnable(){
public void run() {
total.addAndGet(a);
return;
}
});
}

tpool.shutdown(); //wait for everything to finish
try {
tpool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
}
return total.get();
}

关于java - ExecutorService 池中的数组中所有元素的总和不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792668/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com