Code:
class A
{
int x=1,y=1;
static int z;
synchronized void f1()
{
x++;
z++;
System.out.println("Called "+z+" Time");
try
{
Thread.sleep(10000);
}
catch(InterruptedException e){}
System.out.println("(Synchronized)X= "+x);
}
}
class B extends Thread
{
A ab;
B(A aob)
{
ab=aob;
}
public void run()
{
ab.f1();
}
}
class Multi_sync
{
public static void main(String args[])
{
A a1=new A();
A a2=new A();
B b1=new B(a1);
B b2=new B(a2);
b1.start();
b2.start();
}
}
The output of the program is
Called 1 Time
Called 2 Time
(Synchronized)X= 2
(Synchronized)X= 2
Although it should be,
Called 1 Time
(Synchronized)X= 2
Called 2 Time
(Synchronized)X= 2
I don't understand the o/p, because I think if a synchronized method is invoked for the first time, it won't get executed for the 2nd until the first invocation returns the control....is it right?