user3086577
user3086577

Reputation: 101

When you should implement Runnable?

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 ?

Upvotes: 2

Views: 1891

Answers (7)

PNS
PNS

Reputation: 19905

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.

Upvotes: -1

Gray
Gray

Reputation: 116878

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.

Upvotes: 1

user177800
user177800

Reputation:

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.

Upvotes: 2

René Link
René Link

Reputation: 51353

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.

Upvotes: 1

Ace
Ace

Reputation: 1601

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).

Upvotes: -1

ahanin
ahanin

Reputation: 892

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.

Upvotes: 1

kosa
kosa

Reputation: 66637

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()

Upvotes: 0

Related Questions