Thread.Start()如何运行Runnable的run方法?

时间:2016-03-21 09:30:18

标签: java multithreading

我知道Thread实现Runnable。当您从Thread调用start()时,我希望它调用已实现它的run() Runnable方法。

Thread的参数化构造函数之一接受Runnable对象。 即Thread(Runnable target)

现在我想知道,如何从线程的run()方法调用目标start()方法?

他们是否在Thread类中有Runnable的引用?

如果任何人都可以发布start()的定义,那将会很有帮助。

3 个答案:

答案 0 :(得分:3)

是 - Thread对象保留对Runnable的引用,并在其run()方法内调用Runnable的run()方法。

start()方法不参与runnable;其目的是请求调度线程以执行。

你也可以覆盖Thread的run()方法,但这是一个糟糕的设计选择。

答案 1 :(得分:2)

绝对。如果你看一下标准库的Thread.java类,你会看到这一行:

/* 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

答案 2 :(得分:0)

查看Thread class

start()方法的源代码
 /**
     * 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();

在上面的代码中,您看不到run()方法的调用。

private native void start0()负责调用run()方法。 JVM执行此本机方法。