Two threads, one synchronized run(), infinite loop: what behavior is guaranteed?\n\npublic class Q126 implements Runnable {\n private int x; private int y;\n public static void main(String[] args) {\n Q126 that = new Q126();\n (new Thread(that)).start();\n (new Thread(that)).start();\n }\n public synchronized void run() {\n for (;;) {\n x++; y++;\n System.out.println("x = " + x + "y = " + y);\n }\n }\n}

Difficulty: Medium

Correct Answer: x and y are always equal and increase by one each line; one thread monopolizes execution

Explanation:


Introduction / Context:
This test explores synchronization and liveness. Because run() is synchronized on the shared Runnable instance, only one thread can execute it at a time. The infinite loop means the first thread that enters never releases the lock, so the second thread is blocked indefinitely.



Given Data / Assumptions:

  • Two Thread objects share the same Q126 instance.
  • run() is an instance-synchronized method.
  • The loop is for(;;), i.e., never terminates.


Concept / Approach:
Mutual exclusion on the same monitor guarantees that increments of x and y occur together with no interference. Since the loop never ends, the first thread to acquire the monitor will print endlessly. The second thread will remain blocked on the monitor and never print.



Step-by-Step Solution:

Thread T1 acquires monitor on the Q126 object.In each iteration, T1 increments x and y and prints the pair → they remain equal.T2 attempts to enter run(), blocks on the monitor forever because T1 never exits.Output is an increasing sequence (x = 1 y = 1), (x = 2 y = 2), …


Verification / Alternative check:
If the loop had a break or sleep with a synchronized block of smaller scope, the lock could be released and T2 might run later, but as written T1 monopolizes it.



Why Other Options Are Wrong:

  • Compilation errors do not exist on the cited lines.
  • Races (option c) are prevented by synchronization.
  • No deadlock occurs—only starvation of T2.


Common Pitfalls:
Expecting both threads to alternate inside a synchronized infinite loop; misunderstanding that a synchronized method holds the lock for its entire duration.



Final Answer:
x and y are always equal and increase by one each line; one thread monopolizes execution

More Questions from Threads

Discussion & Comments

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