众所周知,java编程语言的内容是极其丰富的,今天我们主要来了解一下java线程生命周期的状态有哪几种,并且展示一个源码实例。
首先,我们需要知道的是线程的任何生命周期,它在任何时刻都只能处于一种状态。同时线程的状态可以通过getState()方法获取,State是一个枚举类,它的位置在Thread中,有六种状态可以被称之为它的生命周期。
第一种是NEW: 它说明线程正处于新建状态,还没有调用start方法,线程生命周期第一个状态。
第二种是RUNNABLE: 可运行状态,在线程抢夺到了CPU时间片的情况下,才会执行,否则处于等待状态。
第三种是BLOCKED:被阻塞状态,主要是因为没有抢夺到synchronized的锁从而导致阻塞。
第四种是WAITING: 等待状态,比如调用了object.wait(),或者thread.join()导致的等待。
第五种是TIMED_WAITING: 计时等待,和上面的情况差不多,只是多了一个计时而已,在有效的时间结束后,线程会被激活。
第六种是TERMINATED: 被终止状态,它是线程生命周期最后的一个状态。
接下来用一个源码来展示。
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; }
以上这些内容都是java学习过程中需要了解的知识,想要了解更多关于java基础,敬请关注奇Q工具网。
推荐阅读: