简体   繁体   English

为什么我们需要一个Runnable来启动线程?

[英]Why do we need a Runnable to start threads?

为什么我们需要在使用Runnable接口创建线程时传递runnable实例?

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. 我们需要将runnable对象传递给线程对象的构造函数的原因是线程必须有一些方法来获取我们希望线程执行的run()方法。

Take an eg 拿一个例如

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; 由于我们不再重写run() Thread类的方法,默认run()执行Thread类的方法; this default run() method looks like this 这个默认的run()方法看起来像这样

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

Hence, ot is the runnable object we passed to the thread's constructor. 因此, ot是我们传递给线程构造函数的可运行对象。 So the thread begins execution with the run() method of the Thread class, which immediately calls the run() method of our runnable object. 因此,线程开始使用Thread类的run()方法执行,该方法立即调用runnable对象的run()方法。

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. Java没有函数指针。 A little trick to solve that problem is to use a object that implements a function. 解决该问题的一个小技巧是使用实现函数的对象。 That function is run . 该功能run So, the object must have a run method. 因此,该对象必须具有run方法。 That is what the Runnable interface does, assure it has a run method. 这就是Runnable接口所做的,确保它有一个run方法。 Thus, if we give a Runnable object, the thread knows what to do! 因此,如果我们给出一个Runnable对象,那么线程就知道该怎么做了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM