public class SynchronizeTest {
public synchronized void methodA() {
System.out.println("calling method a ...");
sleep(2000);
System.out.println("ending method a");
}
public void methodC() {
System.out.println("calling method C");
new Thread(new Runnable() {
@Override
public void run() {
methodA();
}
}).start();
sleep(100);
System.out.println("end method C");
}
public static void main(String[] args) {
new SynchronizeTest().methodC();
}
static void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
At first, I guess because I synchronize
method A, meaning that whole object will be locked until this method is finished. So the answer should be:
calling method C
calling method a
ending method a
ending method C
But turn out, the result something likes:
calling method C
calling method A
ending method C
ending method A
That means methodA
doesn't lock object as I guess. Please tell me why.