InterviewSolution
| 1. |
The yield method of the Thread Class |
|
Answer» The YIELD() method of the Thread class is used to TEMPORARILY stop the EXECUTION of the thread and carry out the execution. For the JAVA.lang.Thread class, the syntax for the yield method is as follows: public static void yield()Execution of a thread is prevented by three ways namely yield(), sleep(), join(). In certain situations where one thread is taking exceedingly more time to complete its execution, we need to find a solution to delay the execution of the thread which completes its execution quickly in between if something important is pending. The yield() provides an answer to this problem. For example, import java.lang.*; class ExampleThread EXTENDS Thread { public void run() { for (int i=0; i<2 ; i++) System.out.println(Thread.currentThread().getName() + " in control"); } } public class Example { public static void main(String[]args) { ExampleThread t = new ExampleThread(); t.start(); // this calls the run() method for (int i=0; i<2; i++) { Thread.yield(); System.out.println(Thread.currentThread().getName() + " in control"); } } }The output of the above program is: $javac Example.java $java Example Thread-0 in control Thread-0 in control main in control main in controlThe output may differ from system to system but the probability of execution of the yield() thread is more. |
|