我环顾四周,似乎无法找到答案。
我正在尝试编写一组包含6个信号量的数组。 [1至6]。
目前,我有这个:
protected static Semaphore[] push;
其次是:
for (int i = 1; i <= 6; i++){
push[i] = new Semaphore(0);
}
我没有收到任何错误:
protected static Semaphore mutex;
mutex = new Semaphore(1);
我收到的错误是:Exception in thread "main" java.lang.NullPointerException
我有一种感觉,它与未声明数组的大小有关,但我并不积极。任何意见都赞赏。
答案 0 :(得分:3)
protected static Semaphore[] push;
在初始化它之前,静态变量是null
(这就是为什么当你试图访问你的数组时你得到NullPointerException。)
您需要初始化数组:
protected static Semaphore[] push = new Semaphore[6];
答案 1 :(得分:1)
正如Brendan所说,Semaphore[] push
未初始化。
Semaphore[] push; // "push" is null at this point (or not initialized)
push[0] = new Semaphore(0); // NullPointerException, because you're accessing
// an array that's in fact still null
push = new Semaphore[6]; // "push" is now an initialized array
push[0] = new Semaphore(0); // is now working
此外,以下工作正常,因为您只是将对象分配给变量:
Semaphore mutex; // "mutex" is not initialized -> null
mutex = new Semaphore(0); // OK, since you're *assigning* the object