1.Java线程到底有几种状态?
有人说是五种(新建、就绪、运行、阻塞、死亡),计算机网络里面讲的线程状态也是这五种,但java线程状态和计网里的线程状态真的一样吗?查阅很多资料,最终从java.lang.Thread.State的源码看到java线程的状态(早期单线程进程状态就是上面的五种)
public enum State {
/**
* Thread state for a thread which has not yet started.
* 1.新建状态
*/
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.
* 2.可运行状态
*/
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}.
* 3.阻塞状态
*/
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 {@code Object.wait()}
* on an object is waiting for another thread to call
* {@code Object.notify()} or {@code Object.notifyAll()} on
* that object. A thread that has called {@code Thread.join()}
* is waiting for a specified thread to terminate.
* 4.等待状态
*/
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>
* 5.超时等待状态
*/
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*6. 终止状态
*/
TERMINATED;
}
2.分析各种状态
- 新建状态:新建一个线程对象,但是还没有调用start方法,此时线程就属于新建状态。
- 可运行状态:处于新建状态的线程被其他线程调用start方法,此时该线程就处于可运行状态,该线程就可以去争夺cpu使用权,获得cpu时间片,如果争夺到了cpu使用权,该线程的程序就会被执行(很多人说可运行状态可以分为就绪和运行,其实就绪状态就是被调用start方法时的状态,运行状态就是争夺到cpu使用权,只不过Java中将这两种状态合成一种了)
- 阻塞状态:此时线程因为某些原因放弃cpu使用权,就处于阻塞状态,直到该线程再次被调用start方法才会重新进入可运行状态。
- 等待状态:此时线程需要等待其他线程做一些特定动作(通知或中断)
- 超时等待状态:此状态不同于等待状态,可以在指定的时间后自动返回
- 终止状态:线程执行完毕,结束生命周期,也称死亡状态
3.各种状态之间转换图