首页 > 代码库 > Thread的run()与start()的区别

Thread的run()与start()的区别

Java的线程是通过java.lang.Thread类来实现的。
VM启动时会有一个由主方法所定义的线程。可以通过创建Thread的实例来创建新的线程。
每个线程都是通过某个特定Thread对象所对应的方法run()来完成其操作的,方法run()称为线程体。
通过调用Thread类的start()方法来启动一个线程。

在Java当中,线程通常都有五种状态,创建、就绪、运行、阻塞和死亡。   
第一是创建状态。在生成线程对象,并没有调用该对象的start方法,这是线程处于创建状态。   
第二是就绪状态。当调用了线程对象的start方法之后,该线程就进入了就绪状态,但是此时线程调度程序还没有把该线程设置为当前线程,此时处于就绪状态。在线程运行之后,从等待或者睡眠中回来之后,也会处于就绪状态。   
第三是运行状态。线程调度程序将处于就绪状态的线程设置为当前线程,此时线程就进入了运行状态,开始运行run函数当中的代码。   
第四是阻塞状态。线程正在运行的时候,被暂停,通常是为了等待某个时间的发生(比如说某项资源就绪)之后再继续运行。sleep,suspend,wait等方法都可以导致线程阻塞。   第五是死亡状态。如果一个线程的run方法执行结束或者调用stop方法后,该线程就会死亡。对于已经死亡的线程,无法再使用start方法令其进入就绪。

A thread can be in only one state at a given point in time. These states are
virtual machine states which do not reflect any operating system thread states.

 

实现并启动线程有两种方法
1、写一个类继承自Thread类,重写run方法。用start方法启动线程
2、写一个类实现Runnable接口,实现run方法。用new Thread(Runnable target).start()方法来启动

多线程原理:
相当于玩游戏机,只有一个游戏机(cpu),可是有很多人要玩,于是,start是排队!等CPU选中你就是轮到你,你就run(),当CPU的运行的时间片执行完,这个线程就继续排队,等待下一次的run()。

调用start()后,线程会被放到等待队列,等待CPU调度,并不一定要马上开始执行,只是将这个线程置于可动行状态。然后通过JVM,线程Thread会调用run()方法,执行本线程的线程体。先调用start后调用run,这么麻烦,为了不直接调用run?就是为了实现多线程的优点,没这个start不行。

1.start()方法来启动线程,真正实现了多线程运行。这时无需等待run方法体代码执行完毕,可以直接继续执行下面的代码;通过调用Thread类的start()方法来启动一个线程, 这时此线程是处于就绪状态, 并没有运行。 然后通过此Thread类调用方法run()来完成其运行操作的, 这里方法run()称为线程体,它包含了要执行的这个线程的内容, Run方法运行结束, 此线程终止。然后CPU再调度其它线程。
2.run()方法当作普通方法的方式调用程序还是要顺序执行,要等待run方法体执行完毕后,才可继续执行下面的代码; 程序中只有主线程——这一个线程, 其程序执行路径还是只有一条, 这样就没有达到写线程的目的。

记住:多线程就是分时利用CPU,宏观上让所有线程一起执行 ,也叫并发

http://blog.csdn.net/xuxurui007/article/details/7685076

Thread相关源码解析(jdk1.6.0_45):

/**     * 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 || this != me)            throw new IllegalThreadStateException();        group.add(this);        start0();        if (stopBeforeStart) {        stop0(throwableFromStop);    }    }    private native void start0();

start()通过invoke native方法start0()来启动新线程。
同一个Thread对象不能start()两次,因为执行过start()后threadStatus就不为0

threadStaus状态对应的值如下:

import java.lang.Thread.State;public class ThreadStausTravel {    public static void main(String[] args) {        State[] status=Thread.State.values();        for (State state : status) {            System.out.println(state.name()+"==>"+state.ordinal());        }    }}

output:
NEW==>0
RUNNABLE==>1
BLOCKED==>2
WAITING==>3
TIMED_WAITING==>4
TERMINATED==>5

Thread.State的源码:

    /**     * A thread state.  A thread can be in one of the following states:      * <ul>     * <li>{@link #NEW}<br>     *     A thread that has not yet started is in this state.     *     </li>     * <li>{@link #RUNNABLE}<br>     *     A thread executing in the Java virtual machine is in this state.      *     </li>     * <li>{@link #BLOCKED}<br>     *     A thread that is blocked waiting for a monitor lock      *     is in this state.      *     </li>     * <li>{@link #WAITING}<br>     *     A thread that is waiting indefinitely for another thread to      *     perform a particular action is in this state.      *     </li>     * <li>{@link #TIMED_WAITING}<br>     *     A thread that is waiting for another thread to perform an action      *     for up to a specified waiting time is in this state.      *     </li>     * <li>{@link #TERMINATED}<br>      *     A thread that has exited is in this state.     *     </li>     * </ul>     *     * <p>     * A thread can be in only one state at a given point in time.      * These states are virtual machine states which do not reflect     * any operating system thread states.     *      * @since   1.5     * @see #getState     */    public enum State {        /**         * Thread state for a thread which has not yet started.         */        NEW,                /**         * Thread state for a runnable thread.  A thread in the runnable         * state is executing in the Java virtual machine but it may         * be waiting for other resources from the operating system         * such as processor.         */        RUNNABLE,                /**         * Thread state for a thread blocked waiting for a monitor lock.         * A thread in the blocked state is waiting for a monitor lock         * to enter a synchronized block/method or          * reenter a synchronized block/method after calling         * {@link Object#wait() Object.wait}.         */        BLOCKED,            /**         * Thread state for a waiting thread.         * A thread is in the waiting state due to calling one of the          * following methods:         * <ul>         *   <li>{@link Object#wait() Object.wait} with no timeout</li>         *   <li>{@link #join() Thread.join} with no timeout</li>         *   <li>{@link LockSupport#park() LockSupport.park}</li>         * </ul>         *          * <p>A thread in the waiting state is waiting for another thread to         * perform a particular action.           *         * For example, a thread that has called <tt>Object.wait()</tt>         * on an object is waiting for another thread to call          * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on          * that object. A thread that has called <tt>Thread.join()</tt>          * is waiting for a specified thread to terminate.         */        WAITING,                /**         * Thread state for a waiting thread with a specified waiting time.         * A thread is in the timed waiting state due to calling one of          * the following methods with a specified positive waiting time:         * <ul>         *   <li>{@link #sleep Thread.sleep}</li>         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>         *   <li>{@link #join(long) Thread.join} with timeout</li>         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>          *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>         * </ul>         */        TIMED_WAITING,        /**         * Thread state for a terminated thread.         * The thread has completed execution.         */        TERMINATED;    }    /**     * Returns the state of this thread.     * This method is designed for use in monitoring of the system state,     * not for synchronization control.     *      * @return this thread‘s state.     * @since 1.5     */    public State getState() {        // get current thread state        return sun.misc.VM.toThreadState(threadStatus);    }

 

 

   /**     * 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)     */    public void run() {    if (target != null) {        target.run();    }    }

run只是普通的方法。

 

Thread的run()与start()的区别