我在Class中有一个静态对象,其中Class是一个writer,然后是该Class的实例,需要引用其中一个静态对象。为了避免代码重复(我必须多次编写相同的代码,每个代码的唯一区别在于使用了哪些静态对象)。
我的解决方案是有一个名为writer1的静态编写器和一个静态编写器调用writer7,然后有一个名为otherWriter的非静态编写器,它在writer1或writer7的构造函数中指向另一个编写器。
但是,当我访问otherWriter时,我不断收到NullPointer异常。错误和代码如下 - 任何想法?
对不起,代码不是很整洁 - 这只是在这个阶段只是瞎傻的hacky。
感谢
错误:
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;
}
}
答案 0 :(得分:2)
在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。