What does “synchronized” exactly do? Lock a function or lock an objects function?

I am wondering how exactly "synchronized" works in java.

Let's say I model a board-game that consists of a number of fields. I implement the fields as a class (Field) and the board as a class (Board) that contains a number of fields. Let's further say I modelled a method moveTo(Player pl) in Field, for a player to move to that field. Each player is represented by a thread.

Although all the threads should do some actions simultaneously (for example rolling their dices), there should only be one player that moves at a time.

How would I ensure that? Is it enough to make the method moveTo(Player pl) synchronized? Or would I need a cascading method in Board to make sure that only one player moves at a time? (Or is there a better solution)?

To bring it to the bottom line:
Would "synchronized" lock a method in EVERY object that has this method or would synchronized lock a method only in the object that is currently in use?
And if the second is the case: is there an easy way to lock a method for every object that has this method implemented?

Thank you!!!

20
задан speendo 25 September 2014 в 21:46
поделиться