0

I am trying to understand synchronization in JAVA. I have written a small program.

class A implements Runnable {
    public void run() {
        Random r = new Random();
        int i = r.nextInt(10);          
        if(i<5){
            print();            
        }else{
        display();  
        }
    }

    public synchronized void display()
    {
        System.out.println("display");
        print();                     // Line no: 19
    } 

    public synchronized void print()
    {
        System.out.println("print");

    }
}


public class Test {
    public static void main(String argv[]) throws Exception {
        A a = new A();
        Thread t = new Thread(a, "A");
        Thread t1 = new Thread(a, "B");
        t.start();
        t1.start();
    }
}

Consider 1st case: I have put a debug point on the 1st line inside print method.

Now when thread A starts running and number randomly generated number 1.

It will call print method and as I have debug point on its first line. It will wait for me to resume.

Now during that time, thread B starts running and number randomly generated number 8.

It should call display method but I see the execution doesn't go inside the display method. It will go inside only after I have make sure that thread A has finished execution.

Shouldn't thread B should go inside display method and wait on the line no 19.

Can two thread generated by same object cannot execute 2 different synchronized method?

Please explain.

Raj
  • 692
  • 2
  • 9
  • 23
  • possible duplicate of [java synchronized method - how does it work](http://stackoverflow.com/questions/14243790/java-synchronized-method-how-does-it-work) – Sotirios Delimanolis Mar 16 '14 at 16:10
  • Looks like a duplicate of a question you asked earlier today, which was answered, and specifically to the point that you are asking here. Please read answers on earlier questions (and mark accepted answer) before asking the same question again. http://stackoverflow.com/questions/22433466/two-threads-executing-two-synchronized-methods/22433513 – Erwin Bolwidt Mar 16 '14 at 16:13

1 Answers1

0

To enter a synchronized method of an object, the thread must acquire the intrinsic lock associated with that object. The lock is bound to the object. Each method doesn't have its own lock.

Since thread A is inside a synchronized method of your Runnable, the other thread must wait for the lock to be released before being able to enter a synchronized method, whether the method is the same or not.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255