Java synchronized keyword not working?

can someone please explain why it's not working?

the output is at the bottom.


  • A bit late, but the reason it is not working is that you have two different objects of type Main (m1 and m2). Synchronized methods prevent multiple concurrent entries to the same method for the same object.

    Here are two ways to fix this:
    1. Make the method static. That will mean the the synchronized keyword will lock at the class level, not the object level.
    2. Make a separate class that holds the sayMsg method and have both thread objects have a reference to the same object (maybe call it messenger). When they call messenger.sayMessage, the synchronization will happen on the sayMessage object.
Sign In or Register to comment.