好吧我一直在做这个作业几个小时了。 对不起,如果英文不好,我刚刚从谷歌翻译。我们将有一个非常特殊的大猩猩,我们将有一个区域(20 x 20阵列),最初我们将有一个区域(20 x 20阵列)。 。将创建5男5只女大猩猩那么我们必须把在随机位置的所有大猩猩会在阵列移动,不能有超过三个大猩猩在一个空间对于这些大猩猩的共存必须遵循下列规则:。同步线程上的NullPointerException
如果在一个单元格中发现两只大猩猩,他们是同性两个大猩猩的一人死亡(这应该是随机进行)如果两个大猩猩有不同的性别,一个新出生(性别,还必须选择随机),他们应该继续各自的方式,我们必须确定sh是并同步所有的线程。“
而且我这样做: 主营:
public static void main(String[] args) {
InformacionGorila info1 = new InformacionGorila(true, 1);
InformacionGorila info2 = new InformacionGorila(true, 2);
Gorilas gorila1 = new Gorilas(info1);
Gorilas gorila2 = new Gorilas(info2);
gorila1.start();
gorila2.start();
}
InformacionGorila类:
public class InformacionGorila {
private boolean genero;
private String sexo;
private int id;
public InformacionGorila(boolean genero, int id) {
this.genero = genero;
this.id = id;
DecisionDeGenero(genero);
}
private void DecisionDeGenero(boolean genero) {
if (genero == true) {
setSexo("Macho");
} else if (genero == false) {
setSexo("Hembra");
}
}
public int getId() {
return id;
}
public boolean getGenero() {
return genero;
}
public void setGenero(boolean genero) {
this.genero = genero;
}
public String getSexo() {
return sexo;
}
private void setSexo(String sexo) {
this.sexo = sexo;
} }
Gorilas类:
public class Gorilas extends Thread {
private final InformacionGorila info;
private Territorio terr;
public Gorilas(InformacionGorila info) {
this.info = info;
}
public InformacionGorila getInfo() {
return info;
}
@Override
public void run() {
try {
terr.Convivencia(info);
System.out.println("Gorila: " + info.getId() + " Genero: " + info.getSexo());
} catch (Exception e) {
System.out.println(e);
}
} }
而且Territorio类:
public class Territorio {
public boolean ocupado = false;
public int cont = 0;
Gorilas[][] gorilas = new Gorilas[20][20];
public synchronized void Convivencia(InformacionGorila info) {
while (ocupado) {
try {
wait();
} catch (InterruptedException ex) {
Logger.getLogger(Territorio.class.getName()).log(Level.SEVERE, null, ex);
}
}
cont++;
if (cont == 2) {
ocupado = true;
}
jaula(info);
}
int j = 0;
int cont2 = 0;
private synchronized void jaula(InformacionGorila info) {
String g = null;
String h = null;
while (cont2 != 2) {
if (j == 0) {
g = info.getSexo();
j++;
} else if (j == 1) {
h = info.getSexo();
}
cont2++;
}
decision(g, h);
}
public void decision(String g, String h) {
if (g.equals(h)) {
InformacionGorila info = new InformacionGorila(true, 11);
Gorilas gorila = new Gorilas(info);
gorila.start();
}
} }
当然还没有结束,但是当我尝试测试它,我得到空指针异常的程序来调用terr.Convivencia(info);
在Gorilas类方法运行时。有人能告诉我为什么吗?哪里不对?或者我做错了什么?
这些是例外:
异常在线程 “线程0” 异常在线程 “线程1”>显示java.lang.NullPointerException 在hilossync.Gorilas.run(Gorilas.java:28 ) 显示java.lang.NullPointerException 在hilossync.Gorilas.run(Gorilas.java:28)
的[什么是空指针异常,以及如何解决?(http://stackoverflow.com/questions/218384/what-is可能的复制-a-null-pointer-exception-and-how-do-i-fix-it) –