为什么我的代码给出“数组索引超出范围”错误?

时间:2019-03-02 01:36:12

标签: java multithreading

我正在编写代码以使用并发线程添加随机元素数组。我想我已经弄清楚了,代码编译没有错误,但是当我运行它时,我得到了超出范围的错误索引,并且找不到问题。

导入java.util。*; 导入java.util.concurrent.atomic.AtomicLong;

公共类总和{

private static final Random RAND = new Random(42); 
   static AtomicLong  total;

public static int[] Random(int length) 
{
    int[] a = new int[length];

    for (int i = 0; i < a.length; i++) 
    {
        a[i] = RAND.nextInt(250_000_000);
    }

    return a;
}


static class Adder implements Runnable
{
        int[] array;
        int lo; 
        int up;
        int length = 250_000_000;  
        int minsum = 0;
      Adder(int[] array, int lo, int up)
      {
         this.array = array;
         this.lo = lo;
         this.up = up;

       }


        public void run()
        {

          for(int i = lo; i < up; i+=1)
          {
              minsum += array[i];
          }

          total.getAndAdd(minsum);

       }

 }



public static void main(String[] args) throws Throwable
{

    int length = 250_000_000;  
    long end = 0;
    long start = 0; 
    int i;
    int[] a = Random(length);
    int threadCount= 1;


    start = System.currentTimeMillis();

    for(i=1; i<=100; i++)
    {
        if (length %i == 0)
            threadCount = i;

            int size = length / threadCount;
            Thread[] threads = new Thread[threadCount];

                for (int j = 1; j <= threadCount; j++)
                {

                    Adder add = new Adder(a, j*size, ((j+1)*size));

                    threads[i] = new Thread(add);
                    threads[i].start();


                }
                for (int t = 1; t <= threadCount; t++)
                {
                    threads[i].join();
                }


        end = System.currentTimeMillis();
        System.out.println(" Using " + i + " threads \n The sum is " + total);
        System.out.println(" The computation took: " + (end - start));   
        total.set(0);

            }




        }



    }

0 个答案:

没有答案