本文是关于JAVA多线程和并发的第三篇,主要介绍一下线程的几个状态的含义。

Thread类源码中规定了几种线程的状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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):创建后尚未启动的线程的状态
  • 运行(Runnable):包含RunningReady两种状态
  • 无限期等待(Waiting):不会被分配CPU执行时间,需要显式被唤醒
    • Timeout参数的Object.wait()方法
    • Timeout参数的Thread.join()方法
    • LockSupport.park()方法
  • 限期等待(Timed Waiting):不会被分配CPU执行时间,在一定时间后会由系统自动唤醒
    • Thread.sleep()方法
    • 设置了Timeout参数的Object.wait()方法
    • 设置了Timeout参数的Thread.join()方法
    • LockSupport.parkNanos()方法
    • LockSupport.parkUntil()方法
  • 阻塞(Blocked):等待获取排他锁
  • 结束(Terminated):已终止线程的状态,线程已经结束执行

既然有这么多线程状态,那么必然会存在状态的转换,他们的状态是如何转换的呢?下面这张图就是比较全面的状态转换图:

image

初学者看到这张图一张是比较晕的,各种乱七八糟的东西堆在这里实在是难以下咽,不过一开始不能完全看懂是很正常的,需要进一步地学习一些细节,不断地来回顾,总有一天就会真正理解了。

下面就是要详细说说Thread类里面的一些方法啦,理解了这些方法,状态的切换图便一目了然。为了限制篇幅,本文先说到这里。