Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
825 views
in Technique[技术] by (71.8m points)

java - Which method calls run()?

public class HelloRunnable implements Runnable {

public void run() {
    System.out.println("Hello from a thread!");
}

public static void main(String args[]) {
    (new Thread(new HelloRunnable())).start();
} } 

According to Java Doc

The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor.

So, When we execute HelloRunnable, who calls the inside run method? In the Thread class, the start method looks like this:

public synchronized void start() {
     if (threadStatus != 0)
         throw new IllegalThreadStateException();
     group.add(this);
     start0();
     if (stopBeforeStart) {
         stop0(throwableFromStop);
     }
 }

From this code, we can see that the start method is not calling the run() method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is stated right in the documentation of start:

the Java Virtual Machine calls the run method of this thread

So, it is the native code in start0 of the JVM that takes care of calling run in the newly created thread. (This is not quite unexpected, as launching a thread is very OS-specific and cannot be implemented in pure Java.)

Note: start0 does not call run directly. Instead (on a high-level view, ignoring JVM-internal management), it instructs the operating system to create a new thread and let that thread execute run.

Just to clarify, here is a short description of the involved methods:

  • start is the high-level function to start a new Thread.

  • start0 is the native method which creates a new Thread from the operating system and is responsible to ensure that run is called.

  • run is the method defined in your Runnable classes. This method is what will be executed in the new thread. A Thread object in Java itself has no idea about the user code it should execute. This is the responsibility of the associated Runnable object.

Thus, when you call Thread.start(), the run method of the Runnable will automatically be called.

Of course, you can always call the run method of a Runnable explicitly:

HelloRunnable hr = new HelloRunnable();
hr.run();

However, this will, of course, not be executed in a separate thread, but block the execution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...