I am not able to understand how the program flow is
I don't know how the method td.start() is in the syschrinized context of the thread td
also how does the thread goes into the synchronized state even if we are not starting the thread
we are starting the thread in the synchronised context
how does the td thread runs the synchronised context before even starting it ?
please help me
here is the code
and the output is
SCJP 6 [86%], OCPWCD [84%], OCEJPAD [83%]
If you find any post useful, click the "plus one" sign on the right
is executed, all it does is to create a (thread) object (it is not yet a thread of execution). This thread object could be used like any other object for synchronization purposes. So all synchronized(td) means is that the main thread now enters a synchronized block and it has to acquire the lock on the 'td' object before it can proceed further. This has nothing to do with the 'td' thread itself. Here we are looking at 'td' as a thread object and not a thread of execution.
But once the main thread enters the synchronized block, then it starts the td thread and td becomes a thread of execution. From this point onwards the two threads could execute in parallel with each other, with no predictable sequence (since we can't predict how the thread scheduler will execute the main thread and the td thread). The td thread itself has a synchroinzed(this) in its code which means it is synchronized on the XMap() instance on which it is executing.
It just happens that the main thread has a Thread.sleep(1000), in which case it just happens we get the output ABC. But XYZ is also a possible result, even though you might not see that happen frequently. Try commenting out the sleep code and you could see that XYZ is a possible output.
encounters, I was thinking that
"the code is synchronized on the object and nothing can enter this code till the execution of object gets completed "
possibly I was wrong here itself
according to your explanation, i came to know that code acquires the lock of the object and then executes the following code
if I am wrong, please correct me
I came to know following points
main thread takes the lock of the object td and then starts executing next code
td.start() is there hence run method also gets called
am I right now?