Thursday, May 29, 2008

start() method vs run() method in Java


start method


public void start() - this method is responsible for causing the thread (it's called upon) to begin execution. The name may seem to be a misnomer here as this method only causes and not actually starts the execution. It just schedules the thread and when the CPU Scheduler picks this thread for excution then the JVM calls the run() method to actually start the execution of the thread.


This method will obviously result into two concurrent threads - one, from which this method is called and two, the new thread which executes the run() method of the new Thread instance.


A thread will throw IllegalStateException in case you try to call the start() method on an already started thread instance. That means, a thread can not be started more than once. As per the Java specifications a thread may not be restarted after completing its execution. You'll be required to create and start the execution of a new thread in that case.


run method


public void run() - this is the only method of the Runnable interface and the classes which intend to execute their code in a separate thread of execution first implement the Runnable interface and subsequently define this method and put all the code expected to be executed in the separate thread inside the scope of this run method.


The other way, such classes can follow for the same is by extending the Thread class and in that case also they should oevrride the run method of the Thread class and put all the code supposed to be executed in the new thread inside the scope of the overriden run method.


Difference between start() and run() methods


start() methods only schedules the thread for execution and not actually begins the execution of the thread. The execution of the thread is started when the JVM calls the run() method of the thread once the CPU Scheduler picks this scheduled thread for execution.



Share/Save/Bookmark


1 comment:

Javin @ arraylist size example said...

Nice post. Just to add once started you can not call start() method on Thread object but you can still call run() method. here are few more differences between start() and run() in Java thread