I am trying to understand below program. If I call new ReaderThread().start() it is working fine, but if I call new ReaderThread().run(), the application goes into an infinite loop. What is the difference?
public class Contention {
private static boolean ready;
private static int number;
private static class ReaderThread extends Thread {
public void run() {
while (!ready){
System.out.println("ready ..."+ready);
Thread.yield();}
System.out.println(number);
// }
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new ReaderThread().run();
number = 42;
ready = true;
}
}
If you use
new ReaderThread().start();,you are creating actually a new thread instance which will run in the background andmain()resumes with its further execution.But
new ReaderThread().run();creates an instance of this class and makes a normal method call to therun()method, so themain()has to wait till therun()has finished executing and returned the control back to main(), which in your case is an infinite loop.If you want to start a new thread then start by using
ReaderThread().start();this is the correct way to start a thread, there are no alternatives for this.