gpt4 book ai didi

Java 线程 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-02 05:39:00 25 4
gpt4 key购买 nike

我用线程编写了一个程序(用于自学),它使用 2 个线程计算数组元素的乘法。但我为两个线程都得到了 ArrayIndexOutOfBoundsException 。错误看起来像这样:

Exception in thread "Thread-1" Exception in thread "Thread-0" Executing multiplying of last2elements
java.lang.ArrayIndexOutOfBoundsException: 1
at FirstPart.run(FirstPart.java:12)
java.lang.ArrayIndexOutOfBoundsException: 1
at SecondPart.run(SecondPart.java:10)

Java 代码:

FirstPart.java

public class FirstPart extends Thread {
int multiply = 1;
static int n;
static int[] v = new int[n];

public void run() {
System.out.println("Executing multiplying of first "+MultiplyDemo.cap1+"elements");
for(int i = 1; i <= MultiplyDemo.cap1; i++) {
multiply = multiply * FirstPart.v[i];
System.out.println("Multiplication is "+ multiply);
}

}
}

SecondPart.java:

public class SecondPart extends Thread {
int multiply = 1;

public void run() {
System.out.println("Executing multiplying of last " + (FirstPart.n - MultiplyDemo.cap1) + "elements");

for(int i = MultiplyDemo.cap1;i <= FirstPart.n; i++) {
multiply=multiply*FirstPart.v[i];
System.out.println("Multiplication is "+multiply);
}
}
}

MultiplyDemo.java:

import java.util.Scanner;
import java.util.Vector;


public class MultiplyDemo {

public static int cap1;


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("introduceti numarul de elemente din vector:");
FirstPart.n=s.nextInt();

int []v=new int[FirstPart.n];
System.out.println("Elementele vectorului sunt");
for(int i = 0; i < v.length; i++)
v[i]=s.nextInt();
cap1=FirstPart.n / 2;

FirstPart thread1=new FirstPart();
SecondPart thread2=new SecondPart();

thread1.start();
thread2.start();

try { // wait for completion of all thread and then sum
thread1.join();
thread2.join(); //wait for completion of MathCos object
double z = thread1.multiply + thread2.multiply;
System.out.println("produsul elementelor este" +z);
}
catch(InterruptedException IntExp) {
}

}
}

最佳答案

数组索引从 0 开始;如果数组的大小为 n有效索引的范围为 0..n-1 .
你所有的for使用 <= 进行循环检查而不是使用<这就是为什么你得到 ArrayIndexOutOfBoundsException .

通常数组上的“for 循环”具有以下形式:

Object[] array = new Object[size];
for(int i = 0;i < array.length;i++) {
..
}

这样你就永远不会超过数组的大小

关于Java 线程 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24671958/

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