What does Runnable bring to the Thread party?

0 Mike Hartigan · February 11, 2015
Excellent series of tutorials.  Thank you very, very much!  

I've been following your Java tutorials and those on www.java2s.com (you complement each other very nicely).  When I'm confused, I can usually get my questions answered by simply viewing the same topic on the other site.  That didn't work with Threads.  Hopefully, my question has a simple answer.

Before discussing the Runnable interface, java2s presents a much simpler way of doing threads.
Briefly:

class MyThreadClass extends Thread {
public void run() {
   System.out.println("Hello Java thread!");
   }
}

Then:
MyThreadClass myThread = new MyThreadClass();
myThread.start();

Java2s then moves on to the Runnable interface, but it doesn't contrast this with the more trivial example cited above.  You don't talk about the trivial technique at all.  Surely, there's a benefit to using Runnable that I'm missing.  Could you clarify?  Or perhaps point me to a more in-depth discussion on this topic?

Thanks,
Mike

Post a Reply

Replies

Oldest  Newest  Rating
0 Mathias Frits Rørvik · February 12, 2015
It is more flexible, remember that you can implement as many interfaces as you want, but you can only extend one class. If you extend Thread. 

Runnable is better, so use Runnable =)
0 Mike Hartigan · February 12, 2015
Not sure that clears it up for me.
Using the trivial example above, I could do the following:

MyThreadClass t1 = new MyThreadClass();
MyThreadClass t2 = new MyThreadClass();
MyThreadClass t3 = new MyThreadClass();
MyThreadClass t4 = new MyThreadClass();

t1.start();
t2.start();
t3.start();
t4.start();

Don't misunderstand -- I'm not arguing that Runnable is not more flexible or somehow 'better'.  Indeed, I'm assuming that it would not even be presented if it wasn't.  I'm simply trying to understand what it buys me.  With all due respect, simply saying it doesn't make it so.
0 Rian F · February 12, 2015
Yes that trivial example works but think of it this way. Every time you use t1 = new MyThreadClass(); you're creating a reference to an object of that type. This means more memory will be used creating these objects. While it is not a problem here, thing of a huge system (such as a game) where efficiency and speed are the key. The runnable interface helps because it makes it so Java can do something like multiple inheritence. I hope this helped a bit in clearing things up for you.  
  • 1

Java / Android Development

107,147 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator