I have simple code:
public class testing {
private static Object objToSync = new Object();
public static void main(String[] args) {
String obj1 = null;
synchronized(objToSync){
System.out.println("something one");
doSomething();
System.out.println("something three ");
}
doSomething();
}
private static void doSomething() {
synchronized(objToSync){
System.out.println("something two");
}
}
I have read several things but still getting confused with this one. Why does the doSomething in the main gets called? Is it not suppose to wait till the synchronized object gets unlocked? Sorry if I am sounding stupid, i am just confused.
The lock is held by the thread, so the fact that you’re synchronizing on it twice (in the case of the first call to
doSomethinginmain) doesn’t matter, it’s on the same thread. If another thread then tried to enter asynchronizedblock onobjToSync, that other thread would wait until this thread released all of its locks.Your code will do this:
mainobjToSyncobjectdoSomethingobjToSyncobjToSyncdoSomethingobjToSyncdoSomethingobjToSyncdoSomethingmainHere’s an example using two threads:
Output: