synchronized block - lock more than one object

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

    Reading all your answers, I tried to apply the following design:

    1. Only lock players, not fields
    2. Do field operations only in synchronized methods/blocks
    3. in a synchronized method/block always first check if the preconditions that caused the synchronized method/block to be called are still the case

    I think 1. avoids deadlocks and 3. is important as things could change while a player waits.

    Further I can go without locking fields as in my game more than one player can stay at a field, only for certain threads an interaction has to be done. This interaction can be done by synchronising players - no need to sync fields...

    What do you think?

提交回复
热议问题