Two Thread subclasses running concurrently — can you predict the exact print order? class s1 extends Thread { public void run() { for (int i = 0; i < 3; i++) { System.out.println("A"); System.out.println("B"); } } } class Test120 extends Thread { public void run() { for (int i = 0; i < 3; i++) { System.out.println("C"); System.out.println("D"); } } public static void main(String args[]) { s1 t1 = new s1(); Test120 t2 = new Test120(); t1.start(); t2.start(); } } Select the correct statement.

Difficulty: Easy

Correct Answer: Will print but not be able to predict the Order

Explanation:


Introduction / Context:
The program launches two independent Thread subclasses. Each thread prints two letters per loop iteration. The question asks if the final interleaving across both threads can be predicted.



Given Data / Assumptions:

  • t1 prints A then B, three times.
  • t2 prints C then D, three times.
  • No synchronization exists between t1 and t2.


Concept / Approach:
Interleaving among different threads is nondeterministic. Within a single thread, A always precedes B and C always precedes D in each loop; however, the relative ordering between the two threads has no guarantee. Therefore you cannot predict a fixed combined pattern like AB CD AB … or ABCD … across the whole output.



Step-by-Step Solution:

Possible output fragment: A B C D A B C D …Another run: C D A B C D …Or even mixed lines: A C B D A B C D … depending on scheduler timing.


Verification / Alternative check:
Introducing Thread.sleep calls can influence but not fully determine the interleaving; exact ordering still varies by platform and load.



Why Other Options Are Wrong:

  • No compile error.
  • Specific patterns (options B and D) are not guaranteed.


Common Pitfalls:
Assuming JVM uses a round-robin scheduler that yields a neat AB-CD alternation.



Final Answer:
Will print but not be able to predict the Order

Discussion & Comments

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