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();
}
First example: No multiple threads. Both execute in single (existing) thread. No thread creation.
r1andr2are just two different objects of classes that implement theRunnableinterface and thus implement therun()method. When you callr1.run()you are executing it in the current thread.Second example: Two separate threads.
t1andt2are objects of the classThread. When you callt1.start(), it starts a new thread and calls therun()method ofr1internally to execute it within that new thread.