gpt4 book ai didi

java - 通过多线程将二维数组传递给类

转载 作者:太空宇宙 更新时间:2023-11-04 12:06:26 27 4
gpt4 key购买 nike

我的程序创建了一个类“MyArray”

class MyArray{
int[][] arr={{14,15,16},{11,12,13}};
}

另一个类“Add_Thread”

class Add_Thread implements Runnable {

private final Matrix RES;
int row;
Thread t;
MyArray arr=new MyArray();

public Add_Thread(Matrix RES,int row) {
this.RES = RES;
t = new Thread(this);
t.start();
this.row = row;
}

public void run() {
synchronized(arr){
for (int i = 0; i < arr.arr[0].length; i++) {
RES.push(arr.arr[row][i]);
}
}
}
}

从“MyArray”获取值并将其推送到另一个类“Matrix”

class Matrix {

final int[][] res_matrix;
int i = 0;
int j = 0;
private int k = 0;
private int l = 0;

public Matrix(int i, int j) {
this.i = i;
this.j = j;
res_matrix = new int[i][j];
}

public synchronized void push(int element) {

int pos1 = k;
int pos2 = l;
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ResultantMatrix.class.getName()).log(Level.SEVERE, null, ex);
}
res_matrix[pos1][pos2] = element;
k++;
l++;
}
}

它存储值并将其发送到 main() 函数

public class Array_demo {

public static void main(String[] args) {
Matrix res = new Matrix(2, 3);
Add_Thread add=new Add_Thread(res, 0);
Add_Thread add2=new Add_Thread(res, 1);
for(int i=0;i<res.res_matrix.length;i++)
{
for(int j=0;j<res.res_matrix[0].length;j++)
{
System.out.print(res.res_matrix[i][j]+" ");
}
System.out.println("");
}
}
}

但是我在 void Push() 方法和 res_matrix[pos1][pos2]=element 中遇到错误。我是线程新手,因此如果能广泛解释我的错误,那就太好了。

输出

0 0 0 
0 0 0
Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: 2
at threading.Matrix.push(Push.java:34)
at threading.Add_Thread.run(Push.java:58)
at java.lang.Thread.run(Thread.java:745)
Exception in thread "Thread-1" java.lang.ArrayIndexOutOfBoundsException: 2
at threading.Matrix.push(Push.java:34)
at threading.Add_Thread.run(Push.java:58)
at java.lang.Thread.run(Thread.java:745)

最佳答案

主要问题是代码:

for (int i = 0; i < arr.arr[0].length; i++) {...}

产生 3 个循环,在每个循环中调用 Matrix.push(...) ,所以push被调用了 3 次。

push方法,你增加索引k每次通话时;从0开始,第一次调用后为1,第二次调用后为2。

当您调用push时第三次,k保存值 2,因为它被分配给变量 pos1 ,当您调用时:

res_matrix[pos1][pos2] = element;

您收到错误:

java.lang.ArrayIndexOutOfBoundsException: 2

因为res_matrix数组的尺寸为 2x3。

关于java - 通过多线程将二维数组传递给类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40316296/

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