Java线程 - NullPointerException

时间:2015-01-11 15:37:08

标签: java android multithreading nullpointerexception

我正在尝试在多个线程上传播一个时间循环,我出于某种原因得到NullPointerException。我检查了thread_array是否为空,但它不是。对我做错的任何建议?这是我的代码:

内线程类

class RowAndThetaThread implements Runnable{
    private int x_0;
    private int y_0;

    public void run() {
        // do something
        thread_semaphore.release();
    }

    public void input_elements(int x, int y) {
        x_0 = x;
        y_0 = y;
        try {
            thread_semaphore.acquire();
        } catch (Exception e) {}
        this.run();
    }

    public void lol() {
        System.out.println("LOLOLOLOL");
    }
}

线程调用

    RowAndThetaThread[] thread_arr = new RowAndThetaThread[LENGTH];

    thread_semaphore = new Semaphore(thread_arr.length, false);
    for (int i=0; i<border_que.arr.length; i++) {
        thread_arr[i].lol(); // NullPointerException happens here
    }

2 个答案:

答案 0 :(得分:1)

您创建线程数组但不初始化数组元素,因此初始化线程数组元素。请参阅以下代码段

RowAndThetaThread[] thread_arr = new RowAndThetaThread[LENGTH];

// Initialization of thread_arr element
for (int i=0; i<border_que.arr.length; i++) {
    thread_arr[i] = new RowAndThetaThread();
}

thread_semaphore = new Semaphore(thread_arr.length, false);
for (int i=0; i<border_que.arr.length; i++) {
    thread_arr[i].lol(); // NullPointerException happens here
}

答案 1 :(得分:1)

问题是您正在为RowAndThetaThread个对象创建一个数组,但是您没有用这些对象填充它。在Java中,默认情况下,对象数组为null。

  // You declare the array here
RowAndThetaThread[] thread_arr = new RowAndThetaThread[LENGTH];
...

thread_arr[i].lol(); // NullPointerException happens here

因为数组中充满了空值,所以你得到NullPointerException。要解决此问题,您必须填充数组。像这样:

RowAndThetaThread[] thread_arr = new RowAndThetaThread[LENGTH];
for(int i = 0; i < thread_arr.length; i++) {
    thread_arr[i] = new RowAndThetaThread();
}
thread_semaphore = new Semaphore(thread_arr.length, false);
for (int i=0; i<border_que.arr.length; i++) {
   thread_arr[i].lol(); // NullPointerException happens here
}