即使在循环中不再满足条件,线程也不会停止

时间:2017-03-24 00:00:50

标签: java multithreading

作为标题,我创建一个线程并从下面的方法newOpponent启动它。

该帖子有一段时间while(OpponentsMap.get(type)!=null&&isPlayerAlive&&game.getFuel()>0.0) 而且我知道线程OpponentsMap.get(type)被更改为null所以现在条件不应该满足它仍然会永远循环。我错过了什么?

public Thread newOpponent(Type type){
    boolean valueSet = true;
    Poi opponent = randomLocationOpponent(type);
    OpponentsMap.replace(type, opponent);

    SwingUtilities.invokeLater(new Runnable() { //Inform EDT about GUI changes
            @Override
            public void run() {
                if(OpponentsMap.get(type)!=null){
                    radar.addPoi(OpponentsMap.get(type));
                }
            }
    });

    Thread thread = new Thread(){
        @Override
        public void run(){
            double[] XYSpeed = getXYSpeedTowardsPlayer(type);

            while(OpponentsMap.get(type)!=null&&isPlayerAlive&&game.getFuel()>0.0){
                moveOpponent(type, XYSpeed[0], XYSpeed[1]);
                System.out.println(OpponentsMap.get(type).getName()+" distance: "+distanceToPlayer(OpponentsMap.get(type)));

                if(distanceToPlayer(OpponentsMap.get(type))>2) {
                    System.out.println("destroy");
                    destroyOpponent(type);
                }
                System.out.println("Is null: "+(OpponentsMap.get(type)==null)+" IsPlayerAlive: "+isPlayerAlive+" isFuelAbove0: "+(game.getFuel()>0.0) );
                try {
                    sleep(300);
                } catch (InterruptedException ex) {
                    Logger.getLogger(GameOpponents.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    };
    return thread;
}

private void destroyOpponent(Type type){
    OpponentsMap.replace(type,null);

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            if(OpponentsMap.get(type)!=null){
                radar.removePoi(OpponentsMap.get(type));

            }
        }
    });
}

更新 我已经尝试将hashmap变为volatile并将其更改为concurrenthashmap,但它仍然没有停止循环。

0 个答案:

没有答案