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
package com.blog;
public class RunnableTest implements Runnable{
@Override
public void run() {
System.out.println(Math.random());
}
public static void main(String[] args) {
RunnableTest runnable = new RunnableTest();
Thread t1 = new Thread(runnable);
t1.start();
Thread t2 = new Thread(runnable);//same runnable instance is shared across threads
t2.start();
Thread t3 = new Thread(runnable);
t3.start();
}
}
Output
0.6704175846914904
0.029629026555648696
0.9349901247103811
Java Code: Extending Thread
package com.blog;
public class ThreadTest extends Thread{
@Override
public void run() {
System.out.println(Math.random());
}
public static void main(String[] args) {
ThreadTest thread1 = new ThreadTest();
thread1.start();
ThreadTest thread2 = new ThreadTest();// We can not restart a thread, so creating a new thread to run the task again
thread2.start();
ThreadTest thread3 = new ThreadTest();
thread3.start();
}
}
Output
0.8411587427953303
0.7752940898558328
0.1213000260889473