简体   繁体   中英

two synchronised blocks at different threads with same object reference still executing simultaneously

public class SynchronizedTest
{
  public static void main(String argv[])
  { 
     Thread t1 = new Thread(new Runnable(){public void run()
     {
        synchronized (this)    //line 7
        {
            for(int i=0; i<100; i++)
                System.out.println("thread A "+i);
        }

    }});
    t1.start();
    synchronized(t1)       // line 15
    {
        for(int i=0; i<100; i++)
            System.out.println("thread B "+i);
    }
  }     
} 

If I understand it correctly, then at line 7 synchronised block references object t1 and at line 15 synchronised block also references the same object so that only one of the threads at a time can acquire a lock on this object and other has to wait.

Then why their contend with each other? Output is mixed like

   thread B 62
   thread B 63 
   thread B 64
   thread A 0
   thread A 1
   thread A 2
   thread B 65
   thread A 3

You are not using the same instance for a lock.

this is the Runnable instance and t1 is the Thread instance

I prefer to declare private static Object LOCK = new Object(); , this is the smallest instance in memory and this is quite simple to know what it is used for.

Edit from the comment (by Steffen Frank)

This has some similarity with synchronized(MyClass.class) but since anyone can access this instance of MyClass.class , anyone can use this lock, so anyone could create a deadlock, using a specific instance give you the hand on it, and let you share it if you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM