Two Runnable instances and two threads — what ordering will the printed numbers follow?\n\nclass s1 implements Runnable \n{ \n int x = 0, y = 0; \n int addX() { x++; return x; } \n int addY() { y++; return y; } \n public void run() { \n for (int i = 0; i < 10; i++) \n System.out.println(addX() + " " + addY()); \n } \n public static void main(String args[]) \n { \n s1 run1 = new s1(); \n s1 run2 = new s1(); \n Thread t1 = new Thread(run1); \n Thread t2 = new Thread(run2); \n t1.start(); \n t2.start(); \n } \n}\n\nSelect the most accurate description.

Difficulty: Easy

Correct Answer: Will print but not exactly in an order (e.g: 1 1 2 2 1 1 3 3...)

Explanation:


Introduction / Context:
The code launches two separate Runnable instances, each with its own counters x and y. The question probes thread interleaving and the independence of state when each thread operates on a different object.



Given Data / Assumptions:

  • run1 and run2 are distinct objects; each thread mutates only its own x and y.
  • There is no synchronization; however, there is no shared state between the threads either.
  • Each thread prints ten lines: "1 1", "2 2", … for its own object.


Concept / Approach:
Because the two threads print concurrently, the console output is an interleaving of two monotonic sequences. Java does not guarantee relative scheduling order, so the lines may mix arbitrarily. What is guaranteed: within each individual thread, the outputs occur in ascending order for that thread.



Step-by-Step Solution:

Thread t1 prints: 1 1, 2 2, 3 3, …Thread t2 prints: 1 1, 2 2, 3 3, …Interleaving may be t1,t2,t1,t2 or t2,t2,t1,… etc.Thus the overall order is not strictly predictable across both threads.


Verification / Alternative check:
Adding Thread.sleep or using thread priorities still does not guarantee a fixed interleaving; only explicit coordination would.



Why Other Options Are Wrong:

  • No compile-time error: start() exists on Thread.
  • A single global sequence (option D) would require shared counters.
  • A strict alternating pattern (option B) is not guaranteed without coordination.


Common Pitfalls:
Assuming deterministic scheduling or thinking that lack of synchronization implies errors even when objects are distinct.



Final Answer:
Will print but not exactly in an order (e.g: 1 1 2 2 1 1 3 3...)

More Questions from Threads

Discussion & Comments

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