Calling yield() inside run() — what will this single-thread program display?\n\npublic class ThreadTest extends Thread \n{ \n public void run() \n { \n System.out.println("In run"); \n yield(); \n System.out.println("Leaving run"); \n } \n public static void main(String [] argv) \n { \n (new ThreadTest()).start(); \n } \n}\n\nChoose the best answer.

Difficulty: Easy

Correct Answer: The text "In run" followed by "Leaving run" will be displayed

Explanation:


Introduction / Context:
This question checks understanding of Thread.yield() and the typical behavior when a single custom thread is launched. yield() is a hint to the scheduler that the current thread is willing to let other runnable threads proceed.



Given Data / Assumptions:

  • Only one user-created thread runs besides the JVM’s background threads.
  • run() prints two lines with a yield() call in between.
  • No exceptions are thrown, and the code compiles cleanly.


Concept / Approach:
yield() does not terminate a thread; it merely gives the scheduler an opportunity to allow another runnable thread to run. In the absence of competing runnable threads with higher or equal priority, the yielding thread is typically scheduled again immediately. Thus both print statements execute in order.



Step-by-Step Solution:

start() → new thread begins executing run().Prints "In run".yield() → scheduler may switch, but usually the same thread continues quickly.Prints "Leaving run".


Verification / Alternative check:
Even with other runnable threads, yield() does not skip code; the same thread will continue later and print the second line.



Why Other Options Are Wrong:

  • There is no compile error.
  • Only printing the first line would imply termination after yield(), which is incorrect.


Common Pitfalls:
Overestimating the power of yield(); it is only a scheduling hint and guarantees nothing beyond allowing other runnable threads a chance.



Final Answer:
The text "In run" followed by "Leaving run" will be displayed

More Questions from Threads

Discussion & Comments

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