简体   繁体   中英

How Thread.Start() runs run method of the Runnable?

I know that Thread implements Runnable . When you call start() from Thread, I hope it calls the run() method of the Runnable from which it has been implemented.

Thread's one of the parameterized constructor accepts Runnable object. ie Thread(Runnable target) .

Now I want to know, How run() method of target is being called from the start() method of the Thread?

Do they have the reference of the Runnable inside Thread class?

It would be helpful if anybody can post the definition of the start() .

Yes - the Thread object keeps a reference to the Runnable, and inside its run() method, calls the Runnable's run() method.

The start() method doesn't get involved with the runnable; its purpose is to request that the Thread be scheduled to execute.

You can also override the Thread's run() method, but that is a poor design choice.

Absolutely. If you look at the Thread.java class of the standard library, you'll see this line:

/* What will be run. */
private Runnable target;

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Thread.java#154

Have a look at source code of start() method in Thread class

 /**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        group.add(this);
        start0();
        if (stopBeforeStart) {
            stop0(throwableFromStop);
        }
    }

    private native void start0();

In above code, you can't see invocation to run() method.

private native void start0() is responsible for calling run() method. JVM executes this native method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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