Two threads calling a synchronized instance method on the same object: what sequence of numbers prints?\n\npublic class ThreadDemo {\n private int count = 1;\n public synchronized void doSomething() {\n for (int i = 0; i < 10; i++) System.out.println(count++);\n }\n public static void main(String[] args) {\n ThreadDemo demo = new ThreadDemo();\n Thread a1 = new A(demo);\n Thread a2 = new A(demo);\n a1.start(); a2.start();\n }\n}\nclass A extends Thread {\n ThreadDemo demo;\n public A(ThreadDemo td) { demo = td; }\n public void run() { demo.doSomething(); }\n}

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:

  • count starts at 1 and is incremented inside a synchronized method.
  • Two threads A operate on the same ThreadDemo instance.
  • Each call prints ten numbers by incrementing count.


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:

Thread T1 enters doSomething(), prints 1..10, exits.Thread T2 then enters doSomething(), prints 11..20.The monitor on demo enforces this serialization.Final output is the numbers 1 through 20, each once, in order.


Verification / Alternative check:
If doSomething() were not synchronized, lines could interleave and ordering would not be guaranteed.



Why Other Options Are Wrong:

  • 0..19 contradicts initial value.
  • “Unknown order with repeats” would require a data race.
  • The code compiles and does not deadlock.


Common Pitfalls:
Assuming threads will interleave inside a synchronized loop; forgetting synchronization scope.



Final Answer:
Prints 1 to 20 sequentially

More Questions from Threads

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion