Thread类源码剖析

Thread类源码剖析

1. 类体

1
2
3
public class Thread implements Runnable { // 实现了Runnable接口
...
}

2. 属性和静态域

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
65
66
67
68
69
70
71
72
73
private static native void registerNatives();//私有静态native方法,实现方法命名的解耦
static {
registerNatives();//静态块,确保创建对象前先调用registerNatives()
}

private volatile String name;//线程名
private int priority;//线程优先级
private Thread threadQ;
private long eetop;

private boolean single_step;//是否单步执行

private boolean daemon = false;//是否守护线程

private boolean stillborn = false;//虚拟机状态

private Runnable target;//将会被执行的Runnable

private ThreadGroup group;//线程所属的线程组

private ClassLoader contextClassLoader;//线程对应的类加载器

private AccessControlContext inheritedAccessControlContext;//线程继承的访问控制环境

private static int threadInitNumber;//自动给匿名线程编号
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}

ThreadLocal.ThreadLocalMap threadLocals = null;//线程对应的ThreadLocal值,此Map由ThreadLocal维护

ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;//线程对应的可继承ThreadLocal值,此Map由InheritableThreadLocal维护
//为子线程提供从父线程那里继承的值
//在创建子线程时,子线程会接收所有可继承的线程局部变量的初始值,以获得父线程所具有的值
//创建一个线程时如果保存了所有 InheritableThreadLocal 对象的值,那么这些值也将自动传递给子线程
//如果一个子线程调用 InheritableThreadLocal 的 get() ,那么它将与它的父线程看到同一个对象

private long stackSize;//线程请求的堆栈大小,一些VM会无视

private long nativeParkEventPointer;//在native线程终止后仍保持的JVM私有状态

private long tid;//每个线程的唯一ID

private static long threadSeqNumber;//用来生成线程ID

private volatile int threadStatus = 0;//线程状态


private static synchronized long nextThreadID() {//得到下个线程的ID
return ++threadSeqNumber;
}

volatile Object parkBlocker;//中断阻塞器,当线程发生IO中断时,需要在线程中断状态后调用此对象的interrupt()
private volatile Interruptible blocker;//阻塞器锁,用来处理阻塞情况
private final Object blockerLock = new Object();//阻断锁

void blockedOn(Interruptible b) {//通过java.nio的sun.misc.SharedSecrets调用,设置blocker
synchronized (blockerLock) {
blocker = b;
}
}

public final static int MIN_PRIORITY = 1;//最小优先级
public final static int NORM_PRIORITY = 5;//默认优先级
public final static int MAX_PRIORITY = 10;//最大优先级


private static final StackTraceElement[] EMPTY_STACK_TRACE
= new StackTraceElement[0];//空堆栈跟踪元素数组


private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
new RuntimePermission("enableContextClassLoaderOverride");

3. 构造函数

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
public Thread() { //默认构造器
init(null, null, "Thread-" + nextThreadNum(), 0);
}
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
Thread(Runnable target, AccessControlContext acc) {
init(null, target, "Thread-" + nextThreadNum(), 0, acc, false);
}
public Thread(ThreadGroup group, Runnable target) {
init(group, target, "Thread-" + nextThreadNum(), 0);
}
public Thread(String name) {
init(null, null, name, 0);
}
public Thread(ThreadGroup group, String name) {
init(group, null, name, 0);
}
public Thread(Runnable target, String name) {
init(null, target, name, 0);
}
public Thread(ThreadGroup group, Runnable target, String name) {
init(group, target, name, 0);
}
public Thread(ThreadGroup group, Runnable target, String name,
long stackSize) {
init(group, target, name, stackSize);
}

4. native函数

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
public static native Thread currentThread();//返回当前正在执行的线程对象的引用

public static native void yield();//可以向调度程序提示当前程序可以让出对处理器的使用,调度器可以忽略此提示。

//使当前线程从执行状态(运行状态)变为可执行态(就绪状态)。cpu会从众多的可执行态里选择,也就是说,当前也就是刚刚的那个线程还是有可能会被再次执行到的,并不是说一定会执行其他线程而该线程在下一次中不会执行到了

public static native void sleep(long millis) throws InterruptedException;//使当前线程休眠一定时间

private native void start0();//native启动线程

private native boolean isInterrupted(boolean ClearInterrupted);//判断是否有线程被中断

public final native boolean isAlive();//判断此线程是否alive,只要已启动并且未死亡即存活。

public static native boolean holdsLock(Object obj);//仅当当前线程在指定的对象上持有monitor lock时返回true

private native static StackTraceElement[][] dumpThreads(Thread[] threads);
private native static Thread[] getThreads();
private native void setPriority0(int newPriority);//设置线程优先级
private native void stop0(Object o);//停止线程
private native void suspend0();// 线程挂起(暂停)
private native void resume0();//将一个挂起线程复活继续执行
private native void interrupt0();//该线程的中断状态将被设置
private native void setNativeName(String name);

@Deprecated
public native int countStackFrames();//弃用

5. 普通函数

5.1 常用

init()

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
65
66
67
68
69
private void init(ThreadGroup g, Runnable target, String name, long stackSize) {//用AccessControlContext初始化一个线程
init(g, target, name, stackSize, null, true);
}

/**
* 线程初始化.
*
* @param g 线程组
* @param target Runnable接口目标对象提供run()
* @param name 线程名
* @param stackSize 所需堆栈大小
* @param acc AccessControlContext
* @param inheritThreadLocals 若为真则继承thread-locals的初始值
*/
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
if (name == null) {//线程name不允许为null
throw new NullPointerException("name cannot be null");
}
this.name = name;

Thread parent = currentThread();//获取当前线程,用来做此线程的父线程
SecurityManager security = System.getSecurityManager();//获取系统的安全管理器SecurityManager
if (g == null) {//若线程组为空
if (security != null) {//且SecurityManager不为空,则根据SecurityManager获取线程组
g = security.getThreadGroup();
}

if (g == null) {//若SecurityManager也没取到线程组,则直接继承当前线程的线程组
g = parent.getThreadGroup();
}
}

g.checkAccess();//一定要检查访问权限

if (security != null) {//SecurityManager不为空时,检查是否有必要的权限
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}

g.addUnstarted();//增加线程组的未启动线程计数
//未启动的线程不会添加到线程组中,以便在从不启动的情况下可以收集这些线程,但必须对它们进行计数,以便不会破坏其中包含未启动线程的守护进程线程组。

//初始化成员属性
//每个线程都有一个优先级,高优先级线程的执行优先于低优先级线程。
//每个线程都可以或不可以标记为一个守护程序。
//当某个线程中运行的代码创建一个新 Thread 对象时,该新线程的初始优先级被设定为创建线程的优先级,
//并且当且仅当创建线程是守护线程时,新线程才是守护程序
this.group = g;
this.daemon = parent.isDaemon();//继承
this.priority = parent.getPriority();
//加载资源的contextClassLoader继承于父线程
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
this.stackSize = stackSize;
//分配一个线程ID
tid = nextThreadID();
}

join()

在中断状态被置位时调用 sleep() 方法并不会使线程休眠,反而会清除此状态并抛出InterruptedException,若在如上循环中加入 sleep() ,则没有必要用 isInterrupted() ,因为不会检测中断状态。

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//线程不会失去监视器的所有权
public static void sleep(long millis, int nanos) throws InterruptedException {//使当前线程休眠一定时间,millis为毫秒,nanos为纳秒
//参数检查
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}

if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}

//纳秒会按规则进到毫秒
if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
millis++;
}

sleep(millis);
}


/**
* 最多等待给定毫秒,有可能线程死亡,当参数为0表示永远等待
* 方法锁当前对象synchronized
*/
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;

if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}

if (millis == 0) {
//条件不满足,继续等待
while (isAlive()) {//当给定0,且线程存活,则一直调用wait(0)一直等待
wait(0);
}
//条件满足,方法返回
} else {
//条件不满足,继续等待
while (isAlive()) {//线程存活,等待给定时间,直到到底时间或线程死亡
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
//条件满足,方法返回
}
}

/**
* 使当前线程休眠一定时间
*/
public final synchronized void join(long millis, int nanos)
throws InterruptedException {

if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}

if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}

if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
millis++;
}

join(millis);
}

/**
* 当前线程一直休眠,直到死亡
*/
public final void join() throws InterruptedException {
join(0);
}

start()和run()

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
public synchronized void start() {//使线程进入可执行状态,告知线程管理器此线程已准备完毕,等待被调用run()
if (threadStatus != 0)//检查线程状态
throw new IllegalThreadStateException();

group.add(this);//告知线程组此线程准备启动,将线程加到线程组中
boolean started = false;
try {
start0();//预启动线程
started = true;//标识已启动
} finally {
try {
if (!started) {//start0()执行失败
group.threadStartFailed(this);//线程组做相应处理
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}

@Override
public void run() {//若线程由Runnable对象构造,则调用对应run(),否则什么都不做,继承Thread时应该重写此方法。
if (target != null) {
target.run();
}
}


Interrupt

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
/**
* 中断线程
*
* 若此线程在调用{Object.wait(),join(),sleep()}方法时被阻塞,则其中断状态会被清除,并抛出异常InterruptedException.
*
* 若线程在执行基于{java.nio.channels.InterruptibleChannel}上的IO操作时被阻塞,则此通道Channel会被关闭,设置线程的中断状态,线程会收到异常{java.nio.channels.ClosedByInterruptException}
*
* 若线程在选择器{@link java.nio.channels.Selector}阻塞,则设置线程的中断状态,并立即从选择操作返回,可能会带有非零值,就像调用了{java.nio.channels.Selector#wakeup wakeup}方法一样。
*
* 非以上情况,设置线程的中断状态,中断一个非alive线程没有任何效果
*/
public void interrupt() {
if (this != Thread.currentThread())//若线程不是在中断自己,则需要检查权限
checkAccess();

synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); //只是设置中断标志
b.interrupt(this);
return;
}
}
interrupt0();
}

/**
* 测试当前线程(current thread)是否已中断
*
* 此方法会清除线程的中断状态,也就意味着若无间断的连续两次调用此方法,第二次调用就会返回false
*/
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}

/**
* 测试此线程(this thread)是否已中断,不改变线程的中断状态
*/
public boolean isInterrupted() {
return isInterrupted(false);
}

5.2 其他

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
public class Thread implements Runnable {//实现Runnable接口

public static native void yield();//不太常用,可以向调度程序提示当前程序可以让出对处理器的使用,调度器可以忽略此提示,用来改善多线程对CPU的过度使用。

@Override
protected Object clone() throws CloneNotSupportedException {//克隆出一个线程
throw new CloneNotSupportedException();
}

private void exit() {//由系统调用,可以让线程在实际退出前可以有机会清理
if (group != null) {
group.threadTerminated(this);
group = null;
}
target = null;
threadLocals = null;
inheritableThreadLocals = null;
inheritedAccessControlContext = null;
blocker = null;
uncaughtExceptionHandler = null;
}


/**
* 更改此线程的优先级
*/
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();//检查权限
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {//正确性检查
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {//能获取到线程组,newPriority也要根据线程组最大限制调整
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}

/**
* 返回此线程的优先级
*/
public final int getPriority() {
return priority;
}

/**
* 更改此线程的线程名
*/
public final synchronized void setName(String name) {
checkAccess();//检查权限
if (name == null) {
throw new NullPointerException("name cannot be null");
}

this.name = name;
if (threadStatus != 0) {
setNativeName(name);
}
}

/**
* 返回此线程的线程名
*/
public final String getName() {
return name;
}

/**
* 返回此线程所属线程组,若线程已死亡,则返回null
*/
public final ThreadGroup getThreadGroup() {
return group;
}

/**
* 返回当前线程的线程组和其子组中所有活动线程的估计数量,即递归迭代当前线程所属线程组所有子组
*/
public static int activeCount() {
return currentThread().getThreadGroup().activeCount();
}

/**
* 将当前线程所属线程组及其子组的所有活动线程复制到指定的数组中,如果数组长度不够,超过的会忽略,若一定要获取所有元素,请先检查线程数量
*/
public static int enumerate(Thread tarray[]) {
return currentThread().getThreadGroup().enumerate(tarray);
}


/**
* 打印当前线程的堆栈跟踪到标准错误流中,仅用于调试
*/
public static void dumpStack() {
new Exception("Stack trace").printStackTrace();
}

/**
* 声明此线程为守护线程或用户线程,若运行的唯一一个线程为守护线程时,JVM会退出。此函数只能在线程声明启动前被调用。
*/
public final void setDaemon(boolean on) {
checkAccess();
if (isAlive()) {
throw new IllegalThreadStateException();
}
daemon = on;
}

/**
* 测试此线程是否为守护线程
*/
public final boolean isDaemon() {
return daemon;
}

/**
* 确认当前正在运行的线程是否有修改此线程的权限
*/
public final void checkAccess() {
SecurityManager security = System.getSecurityManager();
if (security != null) {//如果能取得系统安全管理器,则通过管理器检查此线程权限。
security.checkAccess(this);
}
}

/**
* 返回此线程的字符串表示:线程名+优先级+线程组名
*/
public String toString() {
ThreadGroup group = getThreadGroup();
if (group != null) {
return "Thread[" + getName() + "," + getPriority() + "," +
group.getName() + "]";
} else {
return "Thread[" + getName() + "," + getPriority() + "," +
"" + "]";
}
}

/**
* 返回此线程的ContextClassLoader,此加载器由线程创建者提供,以供加载类和资源时在此线程中运行的代码使用
*/
@CallerSensitive
public ClassLoader getContextClassLoader() {
if (contextClassLoader == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {//检查权限
ClassLoader.checkClassLoaderPermission(contextClassLoader,
Reflection.getCallerClass());
}
return contextClassLoader;
}

/**
* 设置此线程的ContextClassLoader,创建线程时可以设置其ContextClassLoader,允许创建者通过getContextClassLoader获取合适的类加载器
*/
public void setContextClassLoader(ClassLoader cl) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("setContextClassLoader"));
}
contextClassLoader = cl;
}


/**
* 返回此线程堆栈转储的堆栈跟踪元素数组
*/
public StackTraceElement[] getStackTrace() {
if (this != Thread.currentThread()) {
// check for getStackTrace permission
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(
SecurityConstants.GET_STACK_TRACE_PERMISSION);
}
// optimization so we do not call into the vm for threads that
// have not yet started or have terminated
if (!isAlive()) {
return EMPTY_STACK_TRACE;
}
StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
StackTraceElement[] stackTrace = stackTraceArray[0];
// a thread that was alive during the previous isAlive call may have
// since terminated, therefore not having a stacktrace.
if (stackTrace == null) {
stackTrace = EMPTY_STACK_TRACE;
}
return stackTrace;
} else {
// Don't need JVM help for current thread
return (new Exception()).getStackTrace();
}
}

/**
* 返回所有活动线程的堆栈跟踪元素映射,键为线程,值为StackTraceElement元素,其表示对应线程的堆栈转储
*/
public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
// check for getStackTrace permission
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(
SecurityConstants.GET_STACK_TRACE_PERMISSION);
security.checkPermission(
SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
}

// Get a snapshot of the list of all threads
Thread[] threads = getThreads();
StackTraceElement[][] traces = dumpThreads(threads);
Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
for (int i = 0; i < threads.length; i++) {
StackTraceElement[] stackTrace = traces[i];
if (stackTrace != null) {
m.put(threads[i], stackTrace);
}
// else terminated so we don't put it in the map
}
return m;
}


/** cache of subclass security audit results */
/* Replace with ConcurrentReferenceHashMap when/if it appears in a future
* release */
private static class Caches {
/** cache of subclass security audit results */
static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
new ConcurrentHashMap<>();

/** queue for WeakReferences to audited subclasses */
static final ReferenceQueue<Class<?>> subclassAuditsQueue =
new ReferenceQueue<>();
}

/**
* 验证是否可以在不违反安全约束的情况下构造此实例,子类不允许重写安全敏感的非final方法,否则会检查EnableContextClassLoaderOverride运行时权限
*/
private static boolean isCCLOverridden(Class<?> cl) {
if (cl == Thread.class)
return false;

processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
Boolean result = Caches.subclassAudits.get(key);
if (result == null) {
result = Boolean.valueOf(auditSubclass(cl));
Caches.subclassAudits.putIfAbsent(key, result);
}

return result.booleanValue();
}

/**
* 检查给定子类的反射,验证其是否重写了安全敏感的非final方法,若重写返回true,否则false
*/
private static boolean auditSubclass(final Class<?> subcl) {
Boolean result = AccessController.doPrivileged(
new PrivilegedAction<Boolean>() {
public Boolean run() {
for (Class<?> cl = subcl;
cl != Thread.class;
cl = cl.getSuperclass())
{
try {
cl.getDeclaredMethod("getContextClassLoader", new Class<?>[0]);
return Boolean.TRUE;
} catch (NoSuchMethodException ex) {
}
try {
Class<?>[] params = {ClassLoader.class};
cl.getDeclaredMethod("setContextClassLoader", params);
return Boolean.TRUE;
} catch (NoSuchMethodException ex) {
}
}
return Boolean.FALSE;
}
}
);
return result.booleanValue();
}


/**
* 返回线程的ID,线程ID是一个唯一且为正的整型,在线程的生命周期里不能被修改,但线程死亡后可以复用
*/
public long getId() {
return tid;
}

/**
* 线程状态,这些状态是JVM状态而不对应任何操作
*
* 包括:
* {@link #NEW} 尚未启动的线程
* {@link #RUNNABLE} 在JVM中执行的线程处于此状态
* {@link #BLOCKED} 等待监视器锁被阻塞的线程处于此状态
* {@link #WAITING} 无限的等待另一个线程执行特定操作的线程处于此状态
* {@link #TIMED_WAITING} 在指定的等待时间内等待另一个线程执行操作的线程处于此状态
* {@link #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;
}

/**
* 返回此线程的状态,此方法用来监视线程的系统状态,而不是用来作同步控制
*/
public State getState() {
// get current thread state
return sun.misc.VM.toThreadState(threadStatus);
}

//省略了一些异常处理器函数等
...


@Deprecated
public final void stop() {//已弃用,因为不安全
...
}
...

@Deprecated
public void destroy() {//已弃用
throw new NoSuchMethodError();
}

@Deprecated
public final void suspend() {//已弃用
checkAccess();
suspend0();
}

@Deprecated
public final void resume() {//已弃用
checkAccess();
resume0();
}
}