Why do we call the thread object\'s start()
method which in turns calls run()
method, why not we directly call run()
method?
When we use start method then a new thread is created and then code inside the run method will be executed for each new Thread.
Use of start method creates two stack for each thread ,Stack and native stack.
But Run
method call just execute
the code inside the run
method sequentially as run method call does not create different stacks.
Example
import java.util.concurrent.TimeUnit;
public class thread implements Runnable{
/**
* @param args
*/
public static void main(String[] args) {
Thread gg=new Thread(new thread());
Thread gg1=new Thread(new thread());
gg.run();
gg1.start();
/*gg.start();
gg1.start();*/
}
@Override
public void run() {
for(int i=0;i<5;i++)
{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello..." + i);
}
}
}