synchronized block not locking the object reference

前端 未结 3 2046
梦谈多话
梦谈多话 2021-01-24 01:51
class Demo
{
    void demo()
    {
        System.out.println(\"Inside demo of \"+Thread.currentThread().getName());
        try
        {
            Thread.sleep(10000         


        
3条回答
  •  逝去的感伤
    2021-01-24 02:28

    Synchronization is a collaborative effort. Each party states that when another party is in a critical section, they won't be.

    You've only synchronized access to the demo method of the Demo instance in one thread

    synchronized(d)
    {
        d.demo();
    } 
    

    The other is accessing it directly

    d.demo();
    

    They've broken these collaboration rules so you can't assume anything.

    This is explained in the JLS

    Acquiring the lock associated with an object does not in itself prevent other threads from accessing fields of the object or invoking un-synchronized methods on the object. Other threads can also use synchronized methods or the synchronized statement in a conventional manner to achieve mutual exclusion.

提交回复
热议问题