好的,我已经在这个家庭作业上工作了好几个小时了。 对不起如果英语不好我刚刚从谷歌翻译过来。
“对于我们的作业同步线程必须开发野生动物的模拟。将有一种动物。我们将有一种非常特殊的大猩猩。我们将有一个区域(20 x 20阵列)。最初我们将创造5只雄性和5只雌性大猩猩。然后我们必须放置随机位置。所有大猩猩都将在阵中移动,在一个空间中不能有超过三只大猩猩。因为这些大猩猩的共存必须遵循以下规则:
如果在一个细胞中发现两只大猩猩并且它们是同一性别,那么两只大猩猩中的一只死亡(这应该是随机的)如果两只大猩猩有不同的性别,那么新的大猩猩就会出生(必须选择性别)随意)。他们应该继续各自的方式。我们必须识别共享并同步所有线程。“
我这样做了: 主:
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();
}
} }
当然还没有完成,但是当我尝试测试它时,当程序在Gorilas类方法运行中调用terr.Convivencia(info);
时,我得到nullpointer异常。有人可以告诉我为什么吗?怎么了?或者我做错了什么?
这是例外:
线程“Thread-0”中的异常线程“Thread-1”中的异常> java.lang.NullPointerException 在hilossync.Gorilas.run(Gorilas.java:28) 显示java.lang.NullPointerException 在hilossync.Gorilas.run(Gorilas.java:28)
答案 0 :(得分:1)
您已宣布 Territorio terr,但未初始化,使其成为空对象。
它应该更像是
Territorio terr = new Territorio();