Ok. Assuming that this works like they said even if i've tried run this code couple of times and i had "90 90" values once.
But back to the merits. They explain correct answer in that way:
B. The code compiles and runs without issue, so D, E, F, and G are incorrect. The key aspect to notice in the code is that a single-thread executor is used, meaning that no task will be executed concurrently. Therefore, the results are valid and predictable with 100 100 being the output, and B is the correct answer. If a pooled thread executor was used with at least two threads, then the sheepCount2++ operations could overwrite each other, making the second value indeterminate at the end of the program. In this case, C would be the cor- rect answer.
I've changed my code to this one:
And i am still gettin the "100 100" values. What am i doing wrong?
I'd really appreciate if you helped me
To be extra sure of the outcome, add service.awaitTermination() at the end of the code, and then do the printout.
And what about this situation where had also value - 90?
If thought no matter which scenario i choose (single threaded or fixed thread pool) the AtomicInteger always be 100.
It is likely that not all Runnables have been processed at that time. That is why I adviced to put a service.awaitTermination() at the end, bfore printing. Then you know for sure that all Runnables have been processed. So variant 1:
and variant 2:
Ok so whats the difference between and
In the second case, I let the Thread wait until the service was terminated, in which case we know for sure that all Runnables were completed, no matter how much time that would take. I let it wait for max 5 seconds, so in theory I should have checked after 'awairtTermination' if the service had indeed terminated or that the 5 seconds simply were over.
I hope the difference is clear.