Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting Thread behavior in Java [duplicate]

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?

like image 371
avismara Avatar asked Aug 29 '14 09:08

avismara


1 Answers

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.

like image 119
nablex Avatar answered Sep 29 '22 18:09

nablex