I was learning the concept of Multithreading in Java where I came across this very interesting behavior. I was experimenting with various ways of creating a thread. The one under question now is when we are extending a Thread
, not implementing the Runnable
interface.
On a side note, I am aware that it makes perfect OO sense to implement the Runnable
interface rather than to extend the Thread
class, but for the purposes of this question, let's say we extended the Thread
class.
Let t
be my instance of my extended Thread
class and I have a block of code to be executed in the background that is written within my run()
method of my Thread
class.
It perfectly ran in the background with the t.start()
, but I got a bit curious and called t.run()
method. The piece of code executed in the main thread!
What does t.start()
do that t.run()
doesn't?
That is what the class does. The t.start() will actually start a new thread and then calls run() in that thread. If you directly invoke run() you run it in your current thread.
public class Test implements Runnable() {
public void run() { System.out.println("test"); }
}
...
public static void main(String...args) {
// this runs in the current thread
new Test().run();
// this also runs in the current thread and is functionally the same as the above
new Thread(new Test()).run();
// this starts a new thread, then calls run() on your Test instance in that new thread
new Thread(new Test()).start();
}
This is intended behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With