There are two ways to run tasks in separate threads. One is by extending Thread class and another one is by implementing Runnable interface.
What is Runnable?
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
Runnable is the preferred way because of the following reasons:
- Inherit only if you want to override some behavior.So, if you don’t want to override any Thread behavior, then use Runnable.
- Single inheritance: If you extend Thread you cannot extend from any other class, so if that is what you need to do, you have to use Runnable.
- If you develop your task as Runnable, you have all flexibility how to use it now and in the future. You can have it run concurrently via Executors but also via Thread.
- By implementing Runnable, multiple threads can share an instance of your work. If you extended Thread, you’d have to create a new instance of your work for each thread.
- Implementing Runnable makes your code loosely coupled. Because it separates the task from the runner. Extending Thread will make your code tightly coupled. Because, single class will act as both task container as well as runner.
Java Code: Implementing Runnable
Java Code: Extending Thread