线程的生命周期

    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:
         * 
    *
  • {@link Object#wait() Object.wait} with no timeout
  • *
  • {@link #join() Thread.join} with no timeout
  • *
  • {@link LockSupport#park() LockSupport.park}
  • *
* *

A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called Object.wait() * on an object is waiting for another thread to call * Object.notify() or Object.notifyAll() on * that object. A thread that has called Thread.join() * 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: *

    *
  • {@link #sleep Thread.sleep}
  • *
  • {@link Object#wait(long) Object.wait} with timeout
  • *
  • {@link #join(long) Thread.join} with timeout
  • *
  • {@link LockSupport#parkNanos LockSupport.parkNanos}
  • *
  • {@link LockSupport#parkUntil LockSupport.parkUntil}
  • *
*/ TIMED_WAITING, /** * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATED; }

线程的生命周期可以简单归纳为:创建、就绪、运行中、阻塞和结束

创建:当一个Thread类或者其子类的对象被声明并创建的时候,新生的线程对象处在创建状态

就绪:处于新建状态的线程调用start()方法后,将进入线程队列等待CPU时间片,此时他已经具备了运行的条件,只是没有被分配到CPU资源,这时的线程处于就绪态

运行中:当处于就绪态的线程被调度并获取CPU资源的时候,便进入了运行状态,run()方法定义了线程需要执行的操作

阻塞:在某种特殊情况下,线程被人为挂起或执行输入输出操作时,让出CPU的执行权并中止自己的执行,这时线程便进入了阻塞状态

结束:线程完成了他的全部工作,或者线程被提前强制性地终止或出现异常情况导致结束

线程的生命周期_第1张图片

 

你可能感兴趣的:(java)