How does join() work? (Multithreading in Java)
There is something wrong with the answers or the question.
Your understanding of join()
is correct. The "Final value is" message cannot be printed until both threads have completed. The calls to join()
ensures this.
Furthermore, the increment()
method is only called from within a synchronized
block keyed on a static field. So there's no way this method could be called simultaneously by two threads. The "Value is" output is also within the same synchronized block. So there's no access to the value
property from anywhere except within the synchronized block. Therefore, these operations are thread-safe.
The only possible output from this program is "Value is 1. Value is 2. Final value is 2." (In reality, there are no periods or spaces between the outputs - I'm just matching the format of the answers.)
I cannot explain why this matches none of the answers except that whoever wrote the question messed something up.
First i'd like to agree with rlibby. His answer can be proven by writing the program an present the output to the teacher.If we omit that look at this: