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();
}
If you directly call
run()
method, you are not using multi-threading feature sincerun()
method is executed as part of caller thread.If you call
start()
method on Thread, the Java Virtual Machine will call run() method and two threads will run concurrently - Current Thread (main()
in your example) and Other Thread (Runnabler1
in your example).Have a look at source code of
start()
method in Thread classIn above code, you can't see invocation to
run()
method.private native void start0()
is responsible for callingrun()
method. JVM executes this native method.Thread.start()
code registers the Thread with scheduler and the scheduler calls therun()
method. Also,Thread
is class whileRunnable
is an interface.