开发者

Why do we need a Runnable to start threads?

Why we nee开发者_JS百科d to pass the runnable instance while creating the threads using the Runnable interface?


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜