user756611
user756611

Reputation:

Why do we need a Runnable to start threads?

Why we need to pass the runnable instance while creating the threads using the Runnable interface?

Upvotes: 5

Views: 2574

Answers (2)

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46395

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 longer overriding the run() method of the Thread class, the default run() method of the Thread class is executed; 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.

Upvotes: 7

Ishtar
Ishtar

Reputation: 11662

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!

Upvotes: 5

Related Questions