Java: Thread类中start()和run()的区别

版本:JDK1.8

thread的两种使用方式:

//继承Thread类
NewThread thread = new NewThread();//调用默认的构造方法,父类也会调用默认的
thread.start();

    class NewThread extends Thread{
        @Override
        public void run(){
            System.out.println("newThread running==============>");
        }
    }

//使用Runnable对象
Thread thread = new Thread(new RunnableDemo()); thread.start();
class RunnableDemo implements Runnable{ @Override public void run(){ System.out.println("new Runnable running======>"); } }

两种方式对应不同的Thread的构造方法:给target赋值

/**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
     * {@code (null, null, gname)}, where {@code gname} is a newly generated
     * name. Automatically generated names are of the form
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
     */
    public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }
public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}
/** * Initializes a Thread with the current AccessControlContext. * @see #init(ThreadGroup,Runnable,String,long,AccessControlContext,boolean) */ 

private void init(ThreadGroup g, Runnable target, String name, long stackSize) {
init(g, target, name, stackSize, null, true);
}

Thread的start()方法:注释上说明此方法执行时JVM会调用此线程的run方法

/**
     * 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();//一个thread重复调用start的时候会报错

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

    private native void start0();

查看run方法的定义:如果target!=null,调用target.run(),也就是传入的Runnable实例的run方法;如果是用的Thread的子类,则会调用override之后的run方法。

/**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

总结:

start方法是生成新线程的方法,start后jvm会调用run方法。如果只是调用run方法,不会生成新的线程。

猜你喜欢

转载自www.cnblogs.com/jane850113/p/12909223.html