(a) Numbers 1 to 10 will be printed (none repeated or missed) in a serial order.
(b) Numbers 1 to 10 will be printed (none repeated or missed) in any order.
(c) Total of 10 numbers will be printed
(d) The final value of threadcounter just before the program terminates will be 10.
(e) The final value of threadcounter just before the program terminates may be less than 10.
Answer is c and e
I understood c but how can final value of threadCounter be less than 10..
Simple logic says variable is incremented 10 times may be in indefinite manner ..
Think about race conditions in a multi-threaded environment when multiple threads are trying to modify a single resource - in this case threadcounter. The addition operation in line 6 though a single line java code cannot be taken as an atomic operation. It could involve several steps and we can't assume all the steps will be performed in one single run without pause. For example it could happen that a running thread loads threadcounter variable value on its own stack in order to carry out the addition operation but just before it carries out the addition it goes into runnable state. Then another thread comes along and loads the same threadcounter variable value into its own stack (before the first thread having a chance to update it). Now both threads incremement the same value, and update the static variable back on the heap. In this case the threadcounter value will be less than what we intended.
my initial analysis was wrong and i think the answer e should also be wrong. when i ran the program the
number last printed was not consistent. sometimes it prints 9, 6, 7, 10. since it can't be determined the
order in which the thread will print the values.
The main thread creates ten threads in the for loop itself. Their running order is not guranteed, while one is inside the run method some other thread(s) get a chance to run and finish so you will see unordered values printed. The final value would be 10 but the printed order may vary...