线程如何运行?

roc*_*ing 7 java multithreading

我在Threads.上看了一个小例子.为了创建Threads,我们可以通过实现Runnable接口或者通过扩展Thread来做两种方式.我用第一种方式

package test;

public class test implements Runnable{
    public static void main(String args[])
    {
        test t=new test();
        t.run();Thread th=Thread.currentThread();
        th.start();
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("hi");
    }
}
Run Code Online (Sandbox Code Playgroud)

我的疑问是,当我们呼吁th.start();run()是called.I想知道how.I认为内部有start()可能是在提醒run()让我看着Thread类的文档中

以下是start()Thread类中的声明

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();

    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如你在里面看到的那样start(),run()没有被调用但是当我们调用时th.start()会自动覆盖被调用.run()任何人都可以在这里点亮一些

Mar*_*nik 11

run在新线程上调用该方法的机制是extralinguistic:它不能用Java代码表示.这是该start方法的关键路线:

    start0();
Run Code Online (Sandbox Code Playgroud)

start0 是一个本机方法,其调用将:

  • 导致创建新的本机执行线程;
  • 导致run在该线程上调用该方法.