繁体   English   中英

通过多线程将2d数组传递给类

[英]Passing a 2d array to a class through multithreading

我的程序创建了一个类“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] =元素中得到错误。 我是新手,所以如果我的错误被广泛解释会很好。

产量

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被调用三次。

push方法中,您可以在每次调用时增加索引k ; 在第一次呼叫为1之后,在第二次呼叫为2之后,它从0开始。

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

res_matrix[pos1][pos2] = element;

你得到错误:

java.lang.ArrayIndexOutOfBoundsException: 2

因为res_matrix数组的维度为2x3。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM