Hello Java ranches folks !!! My first post in this forums so please be gentle on reaction , and please correct me if something posted incorrectly or not according to rules.
I'm in preparation for my OCPJP 6.0 exam, and doing some mock exams avaliable around the web, here encountered question with some marked correct answers that getting diffuculties to understand why answers marked correct are :
Taken from scjptest.com:
Give a piece of code. Which two are possible results? (Select two)
Answer A,B marked to be correct ...
scjptest.com as explanation provides only link to official SUN now Oracle tutorial about concurrency, that i'm not seeing how it could explain those answers.
By elimination i ruled out answers D and E as not correct, but strugling to understand why C can not occur, or how A and B could occur ...
Is there any strategy to be applied on those non-synchronized multi-threading questions to be applied ?
Answer A is processed in this way:
1. thread 1 sets its local variable, current to 0
2. thread 2 sets its local variable, current to 0. This current is different from thread1's current.
3. thread 1 prints current,0 and then increases current to 2, prints it, increases current to 4, prints it.
4. thread 2 prints its current, 0 , increases it to 2, 4 and prints them out.
5. thread 1 continues to print 6.
6. thread 2 continues to print 6.
Answer C is not possible because:
1. thread 1 sets current to 0,2,4,6 based on the values of a. Thread 1 completes.
2. thread 2 sets current to a, which is 8 and then prints 8 and 10.
Since a is never set to 0 and it is not possible for thread 2 to print 2 and 4.
Joined: May 10, 2012
Thanks Himai Minh , your trace out about C option explains why it can't occur ...
So i think that i should understand this as no magic solution for those kind of questions as truying to rule out what is definitevelly not possible to occur