synchronized block not locking the object reference

前端 未结 3 2038
梦谈多话
梦谈多话 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:25

    So, when MyThread1 is executing, due to the synchronized block, the monitor of d should be locked, resulting in denial of access to d.demo() by the MyThread2.

    That would only happen if MyThread2 also had a synchronized block. When one thread is synchronized on an object, other threads will be blocked if they also try to synchronize on that same object. If they don't synchronize, they won't be. There's nothing that stops access to an object from threads that don't synchronize on it.

    Synchronization is a cooperative mechanism. It only works when all threads work together.

提交回复
热议问题