One shared Runnable with internal synchronization — what will the two threads print?\n\nclass s implements Runnable \n{ \n int x, y; \n public void run() \n { \n for (int i = 0; i < 1000; i++) \n synchronized (this) \n { \n x = 12; \n y = 12; \n } \n System.out.print(x + " " + y + " "); \n } \n public static void main(String args[]) \n { \n s run = new s(); \n Thread t1 = new Thread(run); \n Thread t2 = new Thread(run); \n t1.start(); \n t2.start(); \n } \n}\n\nPredict the console output.

Difficulty: Easy

Correct Answer: It print 12 12 12 12

Explanation:


Introduction / Context:
This code launches two threads sharing a single Runnable instance. Inside run(), assignments to x and y are protected by synchronized(this). The question asks whether the final prints are deterministic and what values will appear.



Given Data / Assumptions:

  • Both threads execute the same run object (this is the same monitor for synchronized).
  • Within the loop, x and y are always set to 12 together while holding the monitor.
  • After the loop, each thread prints x and y without additional synchronization.


Concept / Approach:
Because all writes to x and y happen under the same monitor and always set the same constants (12 and 12), the values cannot diverge. Although the final println occurs outside synchronized, the JMM still guarantees that some assignment has occurred before printing since each thread itself performs the assignments, then prints. There is no deadlock: both synchronized blocks are short and use a single, consistent monitor (this).



Step-by-Step Solution:

Each thread runs the loop 1000 times, repeatedly setting x=12 and y=12 under lock.After its loop finishes, a thread prints x + " " + y + " ". For that thread, the last writes it performed were 12 and 12.Thus the first print is "12 12 ". The second thread does the same, so the combined output is "12 12 12 12" (ordering of the two pairs may vary, but the values are the same).


Verification / Alternative check:
Even without synchronization, constant assignments would still lead to 12 12, but synchronization ensures no torn writes or reordering issues for visibility across threads.



Why Other Options Are Wrong:

  • Deadlock requires circular waits on multiple locks; only one lock is used.
  • Compilation is valid.
  • “Cannot determine” is overly pessimistic; the printed values are deterministically 12 and 12 for each thread.


Common Pitfalls:
Assuming prints must be inside synchronized to see consistent values; here each thread prints its own last writes.



Final Answer:
It print 12 12 12 12

More Questions from Threads

Discussion & Comments

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