0
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
Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205

1 Answers1

2

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.

AxelH
  • 14,325
  • 2
  • 25
  • 55
  • Since the `synchronized` blocks are inside a static method, you could also use the class Object `SynchronizedTest.class` for a lock. See also here: [example](http://tutorials.jenkov.com/java-concurrency/synchronized.html#synchronized-blocks-static-methods) – Steffen Frank May 03 '17 at 12:31
  • @SteffenFrank Indeed but I prefer to use this solution since this is more manageable, I can't restrict the `MyClass.class` access but I can do it for my `LOCK`. This add more security to it. Same with `this` vs `private Object LOCK = new Object()` in a non-static way. – AxelH May 03 '17 at 12:40