Alright - this one is a bit tricky, but I believe I've found the answer. They key is to notice that each thread has it's own instance of an A object. Therefore, both threads could be executing a.aMethod() or a.bMethod() at the same time. Since i is a staic variable, both instances share that variable. Let's take this case: 0. A.i = 0 1. We create two threads, t1 and t2 2. We start both threads, t1 and t2 3. t1 invokes a.aMethod() 4. t1 increments i (i = 1) 5. t1 loses its timeslice before it can assign 1 to i (i it still 0) 6. t2 invokes a.aMethod() 7. t2 increments i (i = 1) 8. t2 assigns 1 to i 9. t2 loses its timeslice to t1 10. t1 assigns 1 to i 11. t1 invokes a.bMethod() 12. t1 decrements i (i = 0) 13. t1 assigns 0 to i 14. t1 loses its timeslice to t2 15. t2 invokes a.bMethod() 16. t2 decrements i (i = -1) 17. t2 assigns -1 to i From this, you can see that, after one cycle of each thread invoking aMethod and bMethod, the value of i is no longer 0. One of the increments was lost due to the fact that the increment was performed but the thread was timesliced out prior to tha assignment being performed. Similarly, you could propose a case in which a decrement would be lost, resulting in a positive value for i. I doubt this conditions would occur very often. That's why the for loop is so large. You need to execute this code many times in order to get the timeslices to occur just right even a few times. I hope that makes sense. :roll: If you have any more questions, please let me know. Corey [ June 04, 2002: Message edited by: Corey McGlone ]
Is it possible that in the exam would appear a question like "Does the code below always print A.i=0? [ June 04, 2002: Message edited by: Francisco A Guimaraes ]
Francisco<br />SCJP<br />please use the [code][/code] tags when showing code.Click <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=ubb_code_page" target="_blank" rel="nofollow">here</a> to see an example.
Joined: Dec 20, 2001
Originally posted by Francisco A Guimaraes: Is it possible that in the exam would appear a question like "Does the code below always print A.i=0? [ June 04, 2002: Message edited by: Francisco A Guimaraes ]
It is possible, but I have a feeling this question is a little more difficult than anything you'd see on the real exam. Of course, on the exam, questions are multiple choice, so they'd probably give you a number of other options, such as "Compiler Error", etc. Corey
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