I thought the answer for this question should be 0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9
But the correct answer turned out to be that the result is unpredictable.
Can any body please explain the reason for that ???
I see that synchronization is playing its role here and I donot understand why the answer would be unpredictable despite some brain storming.
"this" is locking on the instance, and you have an instance of TheA and an instance of TheB.
Two objects, one lock on each, no way to predict outcome.
Even if you had two instances of TheA (or TheB) the answer would be the same; for the same reasons.
If, however, the lock was on the class of TheA (or TheB) or one a singular object (e.g. a TDemo instance) then you would have a predictable outcome
[Hmm...server went funny, Lukas beat me too it. Quick off the mark that guy ]
Joined: Jun 04, 2008
I am not sure I understood the reason that you quoted....I understand that there are two objects...but when those threads run, there is no way a thread can come into execution when the other one is running right ??? Mean to say.......say for example....the A thread is running, it should always be executed completely and then , the B will done completely right ??? Is there any chance that you may get the output saying...
say....0,1,1,2,2,3,4,5,5,3,4.......??? I hope you understood my question ...
Joined: Jun 09, 2009
Err...no. A thread can stop running without warning. The thread scheduler should try and give each thread an equal time at running. That's the theory at any rate - nothing is guaranteed and do not rely on this behaviour!
Anyway, what this means that any any time whilst a thread is running, the scheduler might decide that a thread has had long enough and move it from Running back to Runnable. It will then pick another thread to run and that may well be a different thread. Or the same one; I did say that nothing is guaranteed.
Thus, unless you are very careful with your locks, waits and notifies, there is no guarantee that the a thread will run to completion without being interrupted. In a real-world application you probably wouldn't want a single thread hogging all the processor time anyway.
Joined: Jun 04, 2008
I think I am clear now. Thanks a ton. I appreciate that.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com