synchronized block - lock more than one object

前端 未结 5 928
情书的邮戳
情书的邮戳 2021-01-31 02:26

I\'m modelling a game where multiple players (threads) move at the same time. The information of where a player is located at the moment is stored twice: the player has a variab

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 02:48

    You should not feel bad about your modelling - this is only a two way navigable association.

    If you take care (as in the other answers told) to manipulate atomic, e.g. in the Field methods, thats fine.

    
    public class Field {
    
      private Object lock = new Object();
    
      public removePlayer(Player p) {
        synchronized ( lock) {
          players.remove(p);
          p.setField(null);
        }
      }
    
      public addPlayer(Player p) {
        synchronized ( lock) {
          players.add(p);
          p.setField(this);
        }
      }
    }
    
    
    

    It would be fine if "Player.setField" were protected.

    If you need further atomicity for "move" semantics, go one level up for board.

提交回复
热议问题