Two Thread subclasses running concurrently — can you predict the exact print order?\n\nclass s1 extends Thread\n{ \n public void run() \n { \n for (int i = 0; i < 3; i++) \n { \n System.out.println("A"); \n System.out.println("B"); \n } \n } \n} \nclass Test120 extends Thread \n{ \n public void run() \n { \n for (int i = 0; i < 3; i++) \n { \n System.out.println("C"); \n System.out.println("D"); \n } \n } \n public static void main(String args[]) \n { \n s1 t1 = new s1(); \n Test120 t2 = new Test120(); \n t1.start(); \n t2.start(); \n } \n}\n\nSelect 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