Java synchronization on a shared Runnable instance: how will two threads print shared counters?\n\npublic class Test107 implements Runnable {\n private int x; private int y;\n public static void main(String[] args) {\n Test107 that = new Test107();\n (new Thread(that)).start();\n (new Thread(that)).start();\n }\n public synchronized void run() {\n for (int i = 0; i < 10; i++) {\n x++; y++;\n System.out.println("x = " + x + ", y = " + y);\n }\n }\n}

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:

  • Two Thread objects share the same Test107 instance as their target Runnable.
  • run() is declared synchronized, so it locks on that shared Runnable.
  • x and y are instance fields shared by both threads.


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:

Thread T1 acquires the lock on that, enters run().T1 increments x and y atomically with respect to T2 and prints 10 lines (x = 1..10).T1 exits run(), releases the lock.T2 acquires the lock, prints the next 10 lines (x = 11..20).


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:

  • Interleaving (option b) would occur only if run were not synchronized.
  • Divergence (option d) suggests data races, which synchronization prevents.
  • No compilation or deadlock issues exist.


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)

More Questions from Threads

Discussion & Comments

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