作为标题,我有一个包含枚举列表的类,在该类中我有一个方法newOpponent,它创建了一个线程,我希望当时只运行一个枚举类型的1个线程。
我存储了一个散列图,其中的线程对应于我的枚举;
我正在尝试做的并且不工作是在满足特定条件时调用我的方法destroyOpponent(type)(来自线程)并且此方法从该hashmap中删除线程并且还更改线程中的while条件run()方法所以现在它将为false并再次调用newOpponent(以创建一个新的对象)线程应该完成方法并结束并且应该创建新的方法。
线程实际上从未完成,所以稍后我会多次运行并出现意外结果。
public class GameOpponents {
Radar radar;
Poi player;
public enum Type{
rocket
}
Map<Type, Poi> OpponentsMap = new HashMap();
Map<Type, Thread> OpponentsThreadMap = new HashMap();
public void newOpponent(){
Type type = Type.rocket;
Poi opponent = randomLocationOpponent(type);
OpponentsMap.put(type, opponent);
radar.addPoi(OpponentsMap.get(type));
Thread thread = new Thread(){
@Override
public void run(){
double[] XYSpeed = getXYSpeedTowardsPlayer(type);
while(OpponentsMap.get(type)!=null){
moveOpponent(type, XYSpeed[0], XYSpeed[1]);
if(distanceToPlayer(OpponentsMap.get(type))>2) destroyOpponent(type);
try {
sleep(300);
} catch (InterruptedException ex) {
Logger.getLogger(GameOpponents.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
if(thread.getState()==Thread.State.NEW){
OpponentsThreadMap.put(type, thread);
OpponentsThreadMap.get(type).start();
}
else if(OpponentsThreadMap.get(type).getState()==Thread.State.TERMINATED){
System.out.println("TERMINATED");
OpponentsThreadMap.replace(type, thread);
OpponentsThreadMap.get(type).start();
}
}
private void destroyOpponent(Type type){
radar.removePoi(OpponentsMap.get(type));
OpponentsMap.remove(type);
OpponentsThreadMap.remove(type);
newOpponent();
}