2

I was reading some articles on topic "implement runnable vs extend thread" and I do understand that implementing runnable is prefered because in Java you can't have multiple inheritance. I also read some article that said when you use run() method it just executes the code in current thread, and when you use start() it creates new thread which is I think better, but it depends. But I am still confused about, why you should implement Runnable in class? Why is that needed? Or extending Thread? You can create anonymous thread and start it without implementing runnable or anything.

Sample code of anonymous thread without implementing or extending

new Thread() {
    public void run() {
        System.out.print("Example");
    }
}.start();

EDIT: After some answers and comments, I think what I did not understand was bit more clarified. I actually did not know the reason of implementing Runnable if its run method does not create new Thread. But many of you told me you can use something like this

new Thread(new Runnable())

So finally I want to know - This code up here, does it create a new Thread and executes the code inside the run method ?

user3086577
  • 101
  • 1
  • 10
  • Depends on what APIs you need overridden. – Georgian Jan 07 '14 at 21:36
  • 1
    In most serious cases, you don't directly use threads. you use executors with pools. – njzk2 Jan 07 '14 at 21:37
  • Thread#run executes the Runnable's run method within the current thread context. No new thread is created. Thread#start creates a new thread which will then call the threads run method within the context of the newly create "native" thread... – MadProgrammer Jan 07 '14 at 21:40
  • 1
    pretty much `always` implement `Runnable` or `Callable` you should never in *normal* cases need to sub-class `Thread` directly, if you do, you either know what you are doing and why for a good reason, or you are in way over your head. For advanced cases you should be using `Executors` and the plumbing around them instead of rolling your own. –  Jan 07 '14 at 21:41
  • 1
    Jon Skeet's [answer](http://stackoverflow.com/a/541506/18573) almost five years ago still seems relevant. – Miserable Variable Jan 07 '14 at 21:44
  • 1
    You are extending Thread in that sample code. You are making a [anonymous class](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html) which extends Thread. – Ishtar Jan 07 '14 at 21:46
  • possible duplicate of ["implements Runnable" vs. "extends Thread"](http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread) – Louis Wasserman Jan 07 '14 at 22:07
  • @LouisWasserman It is not duplicate because I know some pros and cons of both ( of course I am not a pro) but I was asking what is the use of Runnable if it does not create new Thread – user3086577 Jan 07 '14 at 22:13

7 Answers7

2

Runnable or Callable is the preferred idiom

Pretty much always implement Runnable or Callable you should never in normal cases need to sub-class Thread directly.

If you do need specialized behavior of the Thread class, you either know what you are doing and why you need a different behavior for the Thread class for a good reason, or you are in way over your head.

Executors are the way to go

For most cases you should be using Executors and the plumbing around them instead of rolling your own when dealing with multiple Threads and their interactions and management.

You should never create a new Thread and manage its life-cycle anymore, error prone and hard to manage, lean on the Executors and leverage them.

Community
  • 1
  • 1
1

When you deal with your own class hierarchy, you don't want to start from the Thread class in the first place. Thread class is an infrastructure for running your Runnables. And there is more, e.g. Executor, etc. Thread holds its state specific to its API. Runnable is a convenient (and a proper) way of wrapping your processing logic and isolate it from the surrounding it should be executed in.

ahanin
  • 892
  • 4
  • 8
1

It depends on your requirements, but in general it is a good idea to seperate What should be done? from Who does it?.

A Thread can execute code, but it has a lifecycle and once it finished you can't start the same Thread instance again.

A Runnable is just some code that can be executed or run(). The lifecycle of the object that implements Runnable is not necessarily bound to a thread's lifecycle and this gives you great benefit:

  • The same Runnable instance can be run multiple times. If you want to re-run a Runnable just create a Thread, pass the Runnable into the thread's constructor and call start().
  • Since a Runnable instance can be re-run easily the instance can remember the previous run's state.
  • The same Runnable instance can be run by multiple threads in parallel.
René Link
  • 48,224
  • 13
  • 108
  • 140
1

why you should implement Runnable in class?

The only way to implement any interface is to define a class. Here are docs on Java interfaces.

Why is that needed? Or extending Thread?

You need to do one or the other if you want to use Thread directly. As others have pointed out, you should take a look at the ExecutorService classes which provide thread-pool support and hide the Thread stuff from the user. Here's the tutorial on the subject.

You can create anonymous thread and start it without implementing runnable or anything.

Your code is an anonymous class that extends Thread. As Ishtar provides, here are the docs about anonymous classes in case there is a question. If you looked at the .class files generated by the Java compiler from your code sample you would see something like Main.class and Main$1.class. Java is actually creating a class for you on the fly.

You could also so an anonymous class which implements Runnable:

new Thread(new Runnable() {
   public void run() {
      System.out.print("Example");
   }
}).start();

But whether or not your use an anonymous class is orthogonal to the question of whether implementing Runnable or extending Thread is the better mechanism to define your thread task. For that question, as @MiserableVariable points out, Jon Skeet's answer is still very relevant.

Community
  • 1
  • 1
Gray
  • 115,027
  • 24
  • 293
  • 354
  • Haha, very literal answer. – Sotirios Delimanolis Jan 07 '14 at 21:54
  • Well, actually I just wanted to know, when to implement Runnable on some class, if you can just simply use anonymous Thread. That was because of the article I read. It said that by implementin Runnable you use run method which does not create new Thread so I was unsure what is use of it then. But now I see you can do Something like you did In the code (Passing new Runnable to Thread). This is what I was looking for – user3086577 Jan 07 '14 at 21:59
0

When you call run() method, it is method invocation on same thread rather than new thread. If you want something happen on separate thread, you either need to extend Thread (or) implement Runnable and call start() on thread object. Java thread life cycle may give you some clarity on difference between calling run() and start()

kosa
  • 65,990
  • 13
  • 130
  • 167
  • Is this possible: `new Thread(new MyObject()).start();` if MyObject implements Runnable? – danihodovic Jan 07 '14 at 21:43
  • 1
    @dani-h: this should help you: http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html – kosa Jan 07 '14 at 21:47
-1

Anonymous classes are useful, but not applicable in most scenarios. This is as true for a Thread class, as for any other type of class.

In cases, for instance, that multiple instantiations of a Thread object are needed and that Thread object also has state (e.g., some calculation results), or communicates with other objects (e.g., via a queue), one has to extend the Thread class, or implementing the Runnable interface and then using a Thread constructor to actually start the thread.

The subject has been discussed extensively, so you can check the answers (and the links) posted to an earlier StackOverflow question, or many other similar ones.

Community
  • 1
  • 1
PNS
  • 19,295
  • 32
  • 96
  • 143
-1

Quoting from the Oracle documentation on Concurrency.

The first idiom, which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread. The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. This lesson focuses on the first approach, which separates the Runnable task from the Thread object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.

Note that the first idiom is Runnable and the second is extending from Thread. It looks like flexibility is the main motivator to go for implementing Runnable approach over extending Thread. I highly doubt if they both map to different implementations by the JVM (although I can't confirm it).

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Ace
  • 1,501
  • 4
  • 30
  • 49
  • _I highly doubt if they both map to different implementations by the JVM_ What are you referring to? `Runnable` and `Thread`? Of course they are different. – Sotirios Delimanolis Jan 07 '14 at 21:46
  • I was referring to thread-management by the JVM... Like PC Register creation, JVM Stack Creation,etc.... (I mean runtime data areas) – Ace Jan 07 '14 at 21:48
  • You should probably rephrase your answer. The term _they_ currently seems to be referring to the `Runnable` and `Thread`. – Sotirios Delimanolis Jan 07 '14 at 21:49
  • Perhaps I should, I was referring to bytecode - to - threading translation by the JVM. Being a novice student of JVM, I can't say this with authority but it looks like all threads are created and managed exactly the same way by JVM regardless of how they are specified in the Java Language... – Ace Jan 07 '14 at 22:00