我在一个类中有一个静态对象,其中该类是一个编写器,然后该类的实例需要引用其中一个静态对象。为了避免代码重复(我必须多次编写相同的代码,每次唯一的区别在于使用哪个静态对象)。
我的解决方案是有一个名为 writer1 的静态写入器和一个名为 writer7 的静态写入器,然后有一个名为 otherWriter 的非静态写入器,它在 writer1 或 writer7 的构造函数中指向另一个写入器。
但是,当我访问 otherWriter 时,我不断收到 NullPointer 异常。下面的错误和代码 - 有什么想法吗?
抱歉,代码并不整洁 - 它很糟糕,因为在这个阶段只是摆弄。
谢谢
错误:
java.lang.NullPointerException
at popl.PoplFormative.generalWrite(PoplFormative.java:108)
at popl.PoplFormative.run(PoplFormative.java:51)
package popl;
import java.util.Arrays;
public class PoplFormative extends Thread {
int currentIndex = 0;
int lastIndexWritten = -1;
static int data[];
int writerId;
static PoplFormative writer1;
static PoplFormative writer7;
PoplFormative otherWriter;
public static void main(String[] args) {
data = new int[10];
writer1 = new PoplFormative(1);
writer7 = new PoplFormative(7);
writer1.start();
writer7.start();
try {
Thread.sleep(600);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Arrays.toString(data));
}
public PoplFormative(int writer) {
this.writerId = writer;
if (writerId == 1) {
this.otherWriter = PoplFormative.writer7;
}
else if (writerId == 7) {
this.otherWriter = PoplFormative.writer1;
}
else {
System.out.println("Big nasty error occurred");
while (true) {
}
}
}
public void run() {
try {
generalWrite();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Exception Thrown");
e.printStackTrace();
}
}
public void generalWrite() throws InterruptedException {
while (currentIndex < 5) {
//System.out.println(writerId + " writer has currentIndex; " + currentIndex);
if (data[Math.max(lastIndexWritten,0)] == writerId || (lastIndexWritten == -1 && writerId == 7)) {
write();
synchronized (this) {
notify();
}
synchronized (otherWriter) {
otherWriter.wait();
}
}
else {
synchronized (otherWriter) {
otherWriter.wait();
write();
}
synchronized (this) {
notify();
}
}
lastIndexWritten += 1;
currentIndex += 1;
}
System.out.println(writerId + " has completed");
}
public void write() {
System.out.println("writer: " + writerId + " currentIndex: " + currentIndex + " lastIndex: " + lastIndexWritten);
data[currentIndex] = writerId;
}
}
最佳答案
在您的 main
中,你有
writer1 = new PoplFormative(1);
调用构造函数
public PoplFormative(int writer) {
this.writerId = writer;
if (writerId == 1) {
this.otherWriter = PoplFormative.writer7;
}
else if (writerId == 7) {
this.otherWriter = PoplFormative.writer1;
}
else {
System.out.println("Big nasty error occurred");
while (true) {
}
}
}
在这种情况下,将执行此代码
if (writerId == 1) {
this.otherWriter = PoplFormative.writer7;
}
但是PoplFormative.writer7
是 null
,因为它还没有初始化,所以 otherWriter
也变成null
。
如果您需要这些循环引用,请考虑使用 setter。
关于java - 使用静态对象的第二个非静态引用时出现 NullPointer 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22896441/