-1
class MyThread extends Thread{
   public void run(){
       print();
   }
   synchronized public void print() {
       // for(int i = 0; i< )
       System.out.println("Thread : " + Thread.currentThread().getName());
       try{
           Thread.sleep(5000);}
           catch(InterruptedException e ){
               
           }
   }
}



public class MyClass {
   public static void main(String args[]) throws InterruptedException {
     
     MyThread t1 = new MyThread();
     MyThread t2 = new MyThread();
     t1.setName("A");
     t2.setName("B");
     t1.start();
     t2.start();
     t1.join();
     t2.join();
     
     System.out.println("EOM");
     
   }
}

Output of the Program -

ThreadA
ThreadB

Immediately prints both line After 5 seconds

EOM

According to my understanding, one of the thread should go in print() and acquire lock and only releases it after 5 seconds but here both the threads executed immediately and then "EOM" got printed after 5 seconds.

2 Answers2

2

The synchronized is in an instance method, and each instance doesn't interfere with each other.

If the method were static then it would be shared between the instances.

Jonas Fagundes
  • 1,519
  • 1
  • 11
  • 18
0

You wrote:

synchronized public void print() {
    ...
}

That's just a short-cut way of writing:

public void print() {
    synchronized(this) {
        ...
    }
}

Each of your two threads is operating on a different instance of your MyClass class, therefore, each of your two threads is synchronizing on a different object (different this reference).

When you use synchronized(o) blocks, that only prevents two different threads from synchronizing on the same object o at the same time.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
  • I am little confused. How can we create two threads thats work on the same object? I mean, when we create thread instance we are creating two objects, right? Can you please explain with an example where two threads acts on the same object? – Abhishek Chaudhary Sep 11 '20 at 16:57
  • @AbhishekChaudhary, That's a separate question. Fortunately, it already has been answered: (see https://stackoverflow.com/q/877096/801894 .) Having two or more threads "work on" the same object is pretty much an essential feature of any multi-threaded program. Working with shared objects is how threads communicate with one another. – Solomon Slow Sep 11 '20 at 17:50