synchronized block - lock more than one object

前端 未结 5 970
情书的邮戳
情书的邮戳 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:55

    A trivial solution would be

    synchronized(player) {
        synchronized(field) {
            // code
        }
    }
    

    However, make sure that you always lock the resources in the same order to avoid deadlocks.

    Note that in practice, the bottleneck is the field, so a single lock on the field (or on a dedicated, common lock object, as @ripper234 rightly pointed out) may suffice (unless you are concurrently manipulating players in other, conflicting ways).

提交回复
热议问题