线程的生命周期
进程和线程
- 进程: 操作系统资源管理的基本单位(Windows系统进入任务管理器,选择进程,即可看到一个个的进程)
- 线程: CPU 调度的基本单位
多线程优点
- 资源利用率更好,利用 CPU 空闲时间处理其他任务
- 某些情况下程序设计更简单
- 提高接口响应速度
线程的生命周期
线程的 6 个状态
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;
}
-
初始状态(NEW)
新创建了一个线程对象,但还没有调用 start() 方法 -
可运行状态(RUNNABLE)
可运行状态的线程位于可运行线程池中,等待被线程调度程序选中,被选中后,获得 CPU 时间片,然后真正执行.
也就是说,可运行状态的线程可能在运行,也可能不在运行,虽然源码中没有进一步细分为两个状态,不过可以参照 linux 的进程状态,进一步将可运行状态细分为就绪状态(READY)和运行中状态(RUNNING) -
阻塞状态(BLOCKED)
当前线程进入 synchronized block/method 时,若 monitor lock 此时被其他线程持有,则当前线程被阻塞,等待其他线程释放锁 -
等待状态(WAITING)
无限期等待其他线程唤醒/终止 -
超时等待状态(TIMED_WAITING)
等待其他线程唤醒/终止,但不用无限期等待,即使其他线程没有操作,达到指定的时间后,也会自动唤醒 -
终止状态(TERMINATED)
线程执行终止,即 run() 方法执行完成.这个线程对象也许还存活着,但它已经不是一个单独执行的线程,线程一旦终止了,不能复生