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.