Runnable or Thread?

Runnable or Thread?

Reading Time: ~ 2 minutes

Should you actually implement Runnable or extend Thread?

If you don’t know what I’m talking than I’ll show some code, however you might have to brush up on your concurrency knowledge 😉

Class Implementing Runnable

public class ClassWithRunnable implements Runnable {
    public void run() {
        // Your code will be here
    }
}

This will be started with a:

new Thread(new ClassWithRunnable()).start();


Class Extending Thread

public class ClassWithThread extends Thread {
    public ClassWithThread() {
        super("MyThread");
    }
    public void run() {
        // Your code will be here
    }
}

This will be started with a:

new ClassWithThread().start();

My Opinion

Well of course both might be used to achieve the same objective, however by following some good practices one can argue that it avoids future headaches.

Point #1 – The case for Multi-Inheritance

By extending the Thread class you cannot extend anymore classes. Unfortunatelly that is Java’s limitation. If you in turn, implements and interface you can still keep on extending multiple-interfaces and of course extend one other class.

Point #2 – The case for Composition

“Composition over Inheritance” is one of the important design principles that one hears about when learning OO programming. I can definitely recommend the book on design patterns from o’reilly if you are interested in the topic.

This point is actually similar to the last one: By composing your class with Runnable you are following the afore mentioned principle and can compose it with other classes, be that by implementing other interfaces or by extending another class.

Point #3 – The case for Deciding at Runtime

By implementing Runnable you are not specializing the behaviour of your thread, you are just giving a thread something, whatever you want, to run. With that, as I explained in another post, you can also decide if you want to run your code in another thread or on the main thread by running start() or run() respectively.

 

Conclusion

Again, it is always your decision since each project is different and has different requirements, thus you need to implement the code the way YOU need, however whenever possible I recommend implementing runnable! Based on my experience this is the most flexible way and demonstrated to be the best way (for my usages).

Leave your opinion, start a discussion, share an experience or just a compliment...

%d bloggers like this: