The method Thread.yield:
Causes the currently executing thread object to temporarily pause and
allow other threads to execute.
So in the following code:
public class Test implements Runnable {
private int stopValue;
public Fib(int stopValue){
this.stopValue = stopValue;
}
@Override
public void run() {
System.out.println("In test thread");
for(int i = 0; i < stopValue; i++){
c = i + 1;
}
System.out.println("Result = "+c);
}
public static void main(String[] args){
int defaultStop = 1024;
if(args.length > 0){
defaultStop = Integer.parseInt(args[0]);
}
Thread a = new Thread(new Fib(defaultStop));
System.out.println("In main");
a.setDaemon(true);
a.start();
Thread.yield();
System.out.println("Back in main");
}
}
I expect that I should see:
In mainthenIn test thread
and the rest would be undefined. But I don’t understand why sometimes I only see:
In main and Back in main and not any print statement from Test thread?
yield() is a hint to the OS scheduled but doesn’t provide any guarantees in terms of scheduling. It doesn’t always pause very long. If you call it repeatly it might only take a few micro-seconds.
Starting a thread takes time and even if you main thread pauses briefly, it may finish before the background thread starts.
As you can see, yield() pauses very briefly.
prints
by comparison, System.nanoTime take longer on my machine.
prints
Both times will vary from OS to OS and machine to machine.