There are 2 ways to create a thread in the Java language, one is by implementing 'Runnable' and the other is by extending the 'Thread' class. In the book I am reading (Herbert Schildt), It's written that implementing the 'Runnable' interface is better, they have duly provided the reasons but I couldn't understand. Could anyone elucidate why there are 2 methods of creating a thread in java and why implementing the interface is a better solution?
-
1We can implement so many classes but can extend only 1.If you extend Thread class then you will block and cant extend any other class.Runnable is interface will be implemented by Thread class – Kick Mar 14 '14 at 18:42
-
A good reason to use `Runnable` (and `Callable`) is also that they can be used in `Executor`s. – fge Mar 14 '14 at 18:57
-
Extending from Thread also prevents the use of your code with any kind of thread pool. Its *much* more flexible to implement Runnable. – Durandal Mar 14 '14 at 19:10
4 Answers
Using Runnable
is better especially given Java supports anonymous temporary classes. Inheriting from Thread
is cumbersome.
This book is a little out of date. There's a third way: use a Callable
instead. That allows you to specify exceptions and have a return type.
Briefly, you submit a Callable
to an executor which returns you a Future
. You can then use that future to examine the return value of the thread.

- 8,319
- 4
- 35
- 78
Implimenting Runnable allows for looser coupling, which is a good design pattern. related (if not dup): "implements Runnable" vs. "extends Thread"

- 1
- 1

- 851
- 6
- 9
Implementing an interface is a good practice compared to extending.You can implement any number of interfaces and can extend only one class.This sums it up.

- 1,834
- 13
- 13
You should use to implement a Runnable, because it is better in the meaning of software design.
For example you can create a abstrace BaseImplementation for all your Runnables. If you inherit from a Thread you can't do it.
But the Book seems to be a pre Java 5 Book. With Java 5 You will have a newer Interface Callable. This interface specifies a returnvalue. Wil the new Executors it ecame easier to start Threads and Threadpools. You should prefer to implement Callables

- 1
- 1

- 15,850
- 5
- 43
- 79