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

时间:2016-10-29 05:23:18

标签: java 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)

1 个答案:

答案 0 :(得分:0)

主要问题是代码:

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。