Difficulty: Medium
Correct Answer: One thread prints all 10 lines first, then the other (guaranteed)
Explanation:
Introduction / Context:
This program examines how method-level synchronization affects the execution of two threads sharing the same Runnable instance. The key is understanding that synchronized instance methods lock on the receiver object (this), creating mutual exclusion across those threads.
Given Data / Assumptions:
Concept / Approach:
Because both threads invoke a synchronized instance method on the same object, only one can enter run() at a time. The first thread to acquire the lock executes the whole for loop (10 iterations) and then releases the lock. The second thread then executes its entire loop. As a result, you see a block of ten ordered lines, followed by another block continuing the count.
Step-by-Step Solution:
Verification / Alternative check:
Removing synchronized would allow interleaving and potentially inconsistent reads/writes on multiprocessor systems (though here only increments happen, divergence still could appear without atomicity).
Why Other Options Are Wrong:
Common Pitfalls:
Forgetting that synchronized on an instance locks that specific object; thinking each iteration releases the lock (it does not).
Final Answer:
One thread prints all 10 lines first, then the other (guaranteed)
Discussion & Comments