I have come across this question and I am just not able to find a good answer to it.
In Java, I can create a thread in 2 ways:
1.Implementing Runnable Interface
public class RunnableInstance implements Runnable {
public void run() {
// functionality goes here
}
}
A new thread created as follows :
public class Client {
public static void main(String[] args) {
RunnableInstance runnableInstance = new RunnableInstance();
Thread thread1 = new Thread(runnableInstance);
thread1.start();
}
}
Advantages of using this method :
- The Client class can inherit any other class.
- The Client class can implement any other interface.
- Creating a thread this way actually separated the job(RunnableInstance) and the runner(Client).
- If the functionality written in
run()
is not required to be run as a separate thread, I can directly use it without creating a thread.
2.Extending the Thread class :
public class ThreadInstance extends Thread {
ThreadInstance() {
super("myThread");
}
public static void main(String[] args) {
new ThreadInstance().start();
}
}
As evident from advantages of using Runnable :
- This class cannot inherit any more classes, as it already extends Thread.
- It mixes job and runner in one class. For these reasons a programmer may prefer to use Runnable.
The Thread class itself implements Runnable interface and provide an empty implementation of run().
## Questions ##
- Why is it done inside Thread class, when we already have a cleaner way to define a job(functionality of a thread)?
I found some answers like a. When we are sure about a thing only being executed asynchronously, we can follow this approach in that case.
b. We can define the job in RunnableInstance's run()
and then execute asynchronously by attaching the Runnable instance to a thread.
OR
We can execute the code inside run()
normally by calling run()
method wherever needed.
In this case, if I know I have to execute a method normally, why would I implement Runnable and then define my functionality inside run()
? I can do it anywhere.
What actually is the reason behind providing these 2 ways of creating threads in Java?
People might find it duplicate, but I did not find a convincing answer. Why 2 ways, when Runnable is the cleaner way? And why would I implement Runnable and write my code in run() ,if I don't have to use it with a thread. What apart from the stuff described above actually let them provide these 2 ways.