You need to know that thread can have different states. Based on http://www.tutorialspoint.com/java/java_multithreading.htm there are 5 states of thread
- new - thread was created and can be started
- runnable - thread is executing
- waiting - thread is waiting for other thread to finish; other thread will have to inform this thread that it finished by calling for example
notify
method on shared lock
- timed waiting - similar to waiting but thread will stop waiting after some time automatically without waiting for signal from other thread
- terminated - thread finished its task
run
method contains only code which needs to be executed when thread will work (when it will be in runnable state).
start
method is needed to take care of changing state of threat from new
to runnable
so it could start working and use its own resources (processor-time for instance) to execute code from run
method.
When you call yourThread.run()
code from run
method will be executed by thread which invoked this method, but if you use yourThread.start()
then code from run
method will be executed using resources of yourThread
.
Take a look at this example
public static void main(String[] args) {
System.out.println("main started");
Thread t = new Thread(){
public void run() {
try {Thread.sleep(2000);} catch (InterruptedException consumeForNow) {}
System.out.println("hello from run");
};
};
t.run();
System.out.println("main ended");
}
Code in run
method will pause thread which runs it for two seconds (because of Thread.sleep(2000);
) so you can see hello from run
after two seconds.
Now output looks like this
main started
hello from run
main ended
because code in run
method was executed by main thread (the one handling public static void main(String[] args)
method), also because of two second pause part
hello from run
main ended
was printed later.
Now if you change t.run()
to t.start()
code in run
method will be executed by t
thread. You will see it by observing result which would be
main started
main ended
(from main stream) and after two seconds
hello from run