Say we have these two Runnables:
class R1 implements Runnable {
public void run() { … }
…
}
class R2 implements Runnable {
public void run() { … }
…
}
Then what's the difference between this:
public static void main() {
R1 r1 = new R1();
R2 r2 = new R2();
r1.run();
r2.run();
}
And this:
public static void main() {
R1 r1 = new R1();
R2 r2 = new R2();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
The difference is that
Thread.start()
starts a thread that calls therun()
method, whileRunnable.run()
just calls therun()
method on the current thread.The difference is that when program calls
start()
method, a new thread is created and code insiderun()
is executed in new thread while if you callrun()
method directly no new thread will be created and code insiderun()
will execute in the current thread directly.Another difference between
start()
andrun()
in Java thread is that you can not callstart()
twice. Once started, secondstart()
call will throwIllegalStateException
in Java while you can callrun()
method several times since it's just an ordinary method.Actually
Thread.start()
creates a new thread and have its own execution scenario.Thread.start()
calls therun()
method asynchronously,which changes the state of new Thread to Runnable.But
Thread.run()
does not create any new thread. Instead it execute the run method in the current running thread synchronously.If you are using
Thread.run()
then you are not using the features of multi threading at all.In the first case you are just invoking the
run()
method of ther1
andr2
objects.In the second case you're actually creating 2 new Threads!
start()
will callrun()
at some point!Start() method call run override method of Thread extended class and Runnable implements interface.
But by calling run() it search for run method but if class implementing Runnable interface then it call run() override method of Runnable.
ex.:
`
`
If you do
run()
in main method, the thread of main method will invoke therun
method instead of the thread you require to run.The
start()
method creates new thread and for which therun()
method has to be done