Why do we need a Runnable to start threads? Why do we need a Runnable to start threads? multithreading multithreading

Why do we need a Runnable to start threads?


The reason we need to pass the runnable object to the thread object's constructor is that the thread must have some way to get to the run() method we want the thread to execute.

Take an e.g

public class CustomApplet extends Applet {          public void init() {                Runnable ot = new OurClass();                Thread th = new Thread(ot);                th.start();         }   }

Since we are no longeroverriding the run() method of the Thread class, the default run() method of the Thread class isexecuted; this default run() method looks like this

public void run() {         if (ot!= null) {                    ot.run();                   }              } 

Hence, ot is the runnable object we passed to the thread's constructor. So the thread begins execution with the run() method of the Thread class, which immediately calls the run() method of our runnable object.


What do you want the new thread to do? You probably want it to execute some code. But what code must it run? You can't just put code in a thread. And Java does not have function pointers. A little trick to solve that problem is to use a object that implements a function. That function is run. So, the object must have a run method. That is what the Runnable interface does, assure it has a run method. Thus, if we give a Runnable object, the thread knows what to do!