Difficulty: Easy
Correct Answer: Prints 1 to 20 sequentially
Explanation:
Introduction / Context:
This problem reinforces how synchronized instance methods serialize access when multiple threads share the same object. Because both threads call the same synchronized method on the same ThreadDemo instance, only one thread at a time executes the loop.
Given Data / Assumptions:
Concept / Approach:
Mutual exclusion ensures that the first thread prints 1..10 in order, then the second thread prints 11..20, also in order. Which thread prints first is not specified, but the overall sequence from 1 to 20 will be strictly increasing without overlap or gaps.
Step-by-Step Solution:
Verification / Alternative check:
If doSomething() were not synchronized, lines could interleave and ordering would not be guaranteed.
Why Other Options Are Wrong:
Common Pitfalls:
Assuming threads will interleave inside a synchronized loop; forgetting synchronization scope.
Final Answer:
Prints 1 to 20 sequentially
Discussion & Comments