For case A) I don't understand how it's possible that both threads (after incrementing a seemingly static variable from within a synchronized block(!)) end up being set to 1 and the final value is thus 1 as well...?

Case C and D are equally confusing to me because I really don't understand how it's possible that main() finishes before both of the required threads (t1 and t2) do. I mean, their join() methods have been called from within the main function, so to my understanding the main function should be required to wait until both t1 and t2 are done with their run() method (and thus have their values printed)...??

2 Answers
2

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.

Or that the answer is simply "none of the above". By the way, there will be no periods or spaces between the print statements (as in Value is 1Value is 2Final value is 2).
–
rlibbyFeb 4 '11 at 15:23

5

You know what they say. Those who can, do. Those who can't, teach.
–
NeilFeb 4 '11 at 15:25

1

Ya, the period thing I just didn't know how to format in another way here on stackoverflow for it to remain readable.
–
wasabiiFeb 4 '11 at 15:25

1

@rlibby +1 for having the eye of a grammar nazi or C compiler.
–
NeilFeb 4 '11 at 15:25

4

Thanks all of you! You are all correct, indeed. I just got in touch with professor (this is one of the questions from an old final exam in my Computer Science course) and it turns out that the PDF contains an error. - Goddamn it! I wasted well over 5 hours on this... Nonetheless thank you very much.
–
wasabiiFeb 4 '11 at 15:31

Who is rlibby? This is not a good answer.As others would be looking at this and asking the same thing, and it does sound like parrotting back some portions of the OP's question.
–
t0mm13bOct 5 '12 at 23:44