I am newbie to java. One doubt.
I read that, int开发者_运维技巧ernally, Thread class's run()
method calls the Runnable interface's run()
.
My Question is,
How the Thread class's run()
method calls the Runnable interface's run()
?
thanks in advance.
The Runnable interface contains only one method: the run()
method. The Thread
class actually
implements the Runnable
interface.
Hence, when you inherit from the Thread class, your subclass also implements the Runnable interface.
Here's an example, how it all happens :
import java.applet.Applet;
public class OurApplet extends Applet {
public void init() {
Runnable ot = new OurClass();
Thread th = new Thread(ot);
th.start();
}
}
The new Thread object's start()
method is called to begin execution of the new thread of control.
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. 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 (target != null) {
target.run();
}
}
Here, target
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.
Essentially, Thread implements Runnable. Thread's run function invokes the "target's" (where target implements Runnable) run method (if it exists). As the code below shows, normally you set the target runnable when creating the Thread object.
NOTE: Runnable is an anonymous class, no need to look to far into it just think of it as a subclass of Runnable.
Runnable run = new Runnable() { public void run() { /* code */ } }; // Create runnable
new Thread(run).start(); // Create thread and start the thread.
精彩评论