-
Notifications
You must be signed in to change notification settings - Fork 669
/
Copy pathThread.java
2245 lines (2027 loc) · 93.6 KB
/
Thread.java
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1994, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.LockSupport;
import jdk.internal.HotSpotIntrinsicCandidate;
import jdk.internal.misc.TerminatingThreadLocal;
import jdk.internal.misc.VM;
import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.Reflection;
import sun.nio.ch.Interruptible;
import sun.security.util.SecurityConstants;
/**
* A <i>thread</i> is a thread of execution in a program. The Java
* Virtual Machine allows an application to have multiple threads of
* execution running concurrently.
* <p>
* Every thread has a priority. Threads with higher priority are
* executed in preference to threads with lower priority. Each thread
* may or may not also be marked as a daemon. When code running in
* some thread creates a new {@code Thread} object, the new
* thread has its priority initially set equal to the priority of the
* creating thread, and is a daemon thread if and only if the
* creating thread is a daemon.
* <p>
* When a Java Virtual Machine starts up, there is usually a single
* non-daemon thread (which typically calls the method named
* {@code main} of some designated class). The Java Virtual
* Machine continues to execute threads until either of the following
* occurs:
* <ul>
* <li>The {@code exit} method of class {@code Runtime} has been
* called and the security manager has permitted the exit operation
* to take place.
* <li>All threads that are not daemon threads have died, either by
* returning from the call to the {@code run} method or by
* throwing an exception that propagates beyond the {@code run}
* method.
* </ul>
* <p>
* There are two ways to create a new thread of execution. One is to
* declare a class to be a subclass of {@code Thread}. This
* subclass should override the {@code run} method of class
* {@code Thread}. An instance of the subclass can then be
* allocated and started. For example, a thread that computes primes
* larger than a stated value could be written as follows:
* <hr><blockquote><pre>
* class PrimeThread extends Thread {
* long minPrime;
* PrimeThread(long minPrime) {
* this.minPrime = minPrime;
* }
*
* public void run() {
* // compute primes larger than minPrime
* . . .
* }
* }
* </pre></blockquote><hr>
* <p>
* The following code would then create a thread and start it running:
* <blockquote><pre>
* PrimeThread p = new PrimeThread(143);
* p.start();
* </pre></blockquote>
* <p>
* The other way to create a thread is to declare a class that
* implements the {@code Runnable} interface. That class then
* implements the {@code run} method. An instance of the class can
* then be allocated, passed as an argument when creating
* {@code Thread}, and started. The same example in this other
* style looks like the following:
* <hr><blockquote><pre>
* class PrimeRun implements Runnable {
* long minPrime;
* PrimeRun(long minPrime) {
* this.minPrime = minPrime;
* }
*
* public void run() {
* // compute primes larger than minPrime
* . . .
* }
* }
* </pre></blockquote><hr>
* <p>
* The following code would then create a thread and start it running:
* <blockquote><pre>
* PrimeRun p = new PrimeRun(143);
* new Thread(p).start();
* </pre></blockquote>
* <p>
* Every thread has a name for identification purposes. More than
* one thread may have the same name. If a name is not specified when
* a thread is created, a new name is generated for it.
* <p>
* Unless otherwise noted, passing a {@code null} argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be
* thrown.
*
* @author unascribed
* @see Runnable
* @see Runtime#exit(int)
* @see #run()
* @see #stop()
* @since 1.0
*/
// 线程
public class Thread implements Runnable {
/**
* The minimum priority that a thread can have.
*/
public static final int MIN_PRIORITY = 1; // 线程最小优先级
/**
* The default priority that is assigned to a thread.
*/
public static final int NORM_PRIORITY = 5; // 线程默认优先级
/**
* The maximum priority that a thread can have.
*/
public static final int MAX_PRIORITY = 10; // 线程最大优先级
/*▼ 线程属性 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┓ */
private volatile String name; // 线程名称
private ThreadGroup group; // 当前线程所处的线程组
private int priority; // 线程优先级
/** Whether or not the thread is a daemon thread. */
private boolean daemon = false; // 当前线程是否为守护线程,默认与父线程属性一致
/**
* Thread ID
*/
private final long tid; // 线程ID
/** What will be run. */
private Runnable target; // 当前线程将要执行的动作
/** The context ClassLoader for this thread */
private ClassLoader contextClassLoader; // 线程上下文类加载器
/** The inherited AccessControlContext of this thread */
private AccessControlContext inheritedAccessControlContext; // 此线程继承的AccessControlContext
/**
* The requested stack size for this thread, or 0 if the creator did not specify a stack size.
* It is up to the VM to do whatever it likes with this number; some VMs will ignore it.
*/
private final long stackSize; // 设置当前线程的栈帧深度(不是所有系统都支持)
/** For autonumbering anonymous threads. */
private static int threadInitNumber; // 下一个线程编号,用于合成线程名
/** For generating thread ID */
private static long threadSeqNumber; // 下一个线程ID
/*▲ 线程属性 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┛ */
// 除非显式设置,否则为空,用于处理未捕获的异常的接口对象
private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
// 除非显式设置,否则为空,用于处理未捕获的异常的接口对象
private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
/**
* Java thread status for tools, default indicates thread 'not yet started'
*/
private volatile int threadStatus; // 线程状态
private static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0]; // 空栈帧
/**
* The argument supplied to the current call to java.util.concurrent.locks.LockSupport.park.
* Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
* Accessed using java.util.concurrent.locks.LockSupport.getBlocker
*/
volatile Object parkBlocker; // 此对象不为null时说明线程进入了park(阻塞)状态,参见LockSupport
/**
* The object in which this thread is blocked in an interruptible I/O operation, if any.
* The blocker's interrupt method should be invoked after setting this thread's interrupt status.
*/
// 线程中断回调标记,设置此标记后,可在线程被中断时调用标记对象的回调方法
private volatile Interruptible blocker;
// 临时使用的锁,在设置/获取线程中断回调标记时使用
private final Object blockerLock = new Object(); // 中断线程时
/**
* ThreadLocal values pertaining to this thread.
* This map is maintained by the ThreadLocal class.
*/
// 线程局部缓存,这是一个键值对组合,为当前线程关联一些“独享”变量,ThreadLocal是key。
ThreadLocal.ThreadLocalMap threadLocals = null;
/**
* InheritableThreadLocal values pertaining to this thread.
* This map is maintained by the InheritableThreadLocal class.
*/
// 从父线程继承而来的线程局部缓存,由InheritableThreadLocal维护
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
/*
* The following three initially uninitialized fields are exclusively managed by class java.util.concurrent.ThreadLocalRandom.
* These fields are used to build the high-performance PRNGs in the concurrent code, and we can not risk accidental false sharing.
* Hence, the fields are isolated with @Contended.
*
* 以下三个字段由java.util.concurrent.ThreadLocalRandom管理
* 这些字段用于在并发代码中构建高性能非重复随机值
*/
/** The current seed for a ThreadLocalRandom */
// 本地化的原始种子
@jdk.internal.vm.annotation.Contended("tlr")
long threadLocalRandomSeed;
/** Secondary seed isolated from public ThreadLocalRandom sequence */
// 本地化的辅助种子
@jdk.internal.vm.annotation.Contended("tlr")
int threadLocalRandomSecondarySeed;
/** Probe hash value; nonzero if threadLocalRandomSeed initialized */
// 本地化的探测值,如果ThreadLocalRandom已经初始化,则该值不为0
@jdk.internal.vm.annotation.Contended("tlr")
int threadLocalRandomProbe;
/* 以下字段由虚拟机设置 */
/** Fields reserved for exclusive use by the JVM */
private boolean stillborn = false;
/** JVM-private state that persists after native thread termination. */
private long nativeParkEventPointer;
private long eetop;
static {
registerNatives();
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}
* {@code (null, null, gname)}, where {@code gname} is a newly generated
* name. Automatically generated names are of the form
* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
*/
// ▶ 1-1-1
public Thread() {
this(null, null, "Thread-" + nextThreadNum(), 0);
}
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}
* {@code (null, target, gname)}, where {@code gname} is a newly generated
* name. Automatically generated names are of the form
* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
*
* @param target the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this classes {@code run} method does
* nothing.
*/
// ▶ 1-1-2
public Thread(Runnable target) {
this(null, target, "Thread-" + nextThreadNum(), 0);
}
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}
* {@code (group, target, gname)} ,where {@code gname} is a newly generated
* name. Automatically generated names are of the form
* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
*
* @param group the thread group. If {@code null} and there is a security
* manager, the group is determined by {@linkplain
* SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
* If there is not a security manager or {@code
* SecurityManager.getThreadGroup()} returns {@code null}, the group
* is set to the current thread's thread group.
* @param target the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this thread's run method is invoked.
*
* @throws SecurityException if the current thread cannot create a thread in the specified
* thread group
*/
// ▶ 1-1-3
public Thread(ThreadGroup group, Runnable target) {
this(group, target, "Thread-" + nextThreadNum(), 0);
}
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}
* {@code (null, null, name)}.
*
* @param name the name of the new thread
*/
// ▶ 1-1-4
public Thread(String name) {
this(null, null, name, 0);
}
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}
* {@code (group, null, name)}.
*
* @param group the thread group. If {@code null} and there is a security
* manager, the group is determined by {@linkplain
* SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
* If there is not a security manager or {@code
* SecurityManager.getThreadGroup()} returns {@code null}, the group
* is set to the current thread's thread group.
* @param name the name of the new thread
*
* @throws SecurityException if the current thread cannot create a thread in the specified
* thread group
*/
// ▶ 1-1-5
public Thread(ThreadGroup group, String name) {
this(group, null, name, 0);
}
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}
* {@code (null, target, name)}.
*
* @param target the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this thread's run method is invoked.
* @param name the name of the new thread
*/
// ▶ 1-1-6
public Thread(Runnable target, String name) {
this(null, target, name, 0);
}
/**
* Allocates a new {@code Thread} object so that it has {@code target}
* as its run object, has the specified {@code name} as its name,
* and belongs to the thread group referred to by {@code group}.
*
* <p>If there is a security manager, its
* {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
* method is invoked with the ThreadGroup as its argument.
*
* <p>In addition, its {@code checkPermission} method is invoked with
* the {@code RuntimePermission("enableContextClassLoaderOverride")}
* permission when invoked directly or indirectly by the constructor
* of a subclass which overrides the {@code getContextClassLoader}
* or {@code setContextClassLoader} methods.
*
* <p>The priority of the newly created thread is set equal to the
* priority of the thread creating it, that is, the currently running
* thread. The method {@linkplain #setPriority setPriority} may be
* used to change the priority to a new value.
*
* <p>The newly created thread is initially marked as being a daemon
* thread if and only if the thread creating it is currently marked
* as a daemon thread. The method {@linkplain #setDaemon setDaemon}
* may be used to change whether or not a thread is a daemon.
*
* @param group the thread group. If {@code null} and there is a security
* manager, the group is determined by {@linkplain
* SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
* If there is not a security manager or {@code
* SecurityManager.getThreadGroup()} returns {@code null}, the group
* is set to the current thread's thread group.
* @param target the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this thread's run method is invoked.
* @param name the name of the new thread
*
* @throws SecurityException if the current thread cannot create a thread in the specified
* thread group or cannot override the context class loader methods.
*/
// ▶ 1-1-7
public Thread(ThreadGroup group, Runnable target, String name) {
this(group, target, name, 0);
}
/**
* Allocates a new {@code Thread} object so that it has {@code target}
* as its run object, has the specified {@code name} as its name,
* and belongs to the thread group referred to by {@code group}, and has
* the specified <i>stack size</i>.
*
* <p>This constructor is identical to {@link
* #Thread(ThreadGroup, Runnable, String)} with the exception of the fact
* that it allows the thread stack size to be specified. The stack size
* is the approximate number of bytes of address space that the virtual
* machine is to allocate for this thread's stack. <b>The effect of the
* {@code stackSize} parameter, if any, is highly platform dependent.</b>
*
* <p>On some platforms, specifying a higher value for the
* {@code stackSize} parameter may allow a thread to achieve greater
* recursion depth before throwing a {@link StackOverflowError}.
* Similarly, specifying a lower value may allow a greater number of
* threads to exist concurrently without throwing an {@link
* OutOfMemoryError} (or other internal error). The details of
* the relationship between the value of the {@code stackSize} parameter
* and the maximum recursion depth and concurrency level are
* platform-dependent. <b>On some platforms, the value of the
* {@code stackSize} parameter may have no effect whatsoever.</b>
*
* <p>The virtual machine is free to treat the {@code stackSize}
* parameter as a suggestion. If the specified value is unreasonably low
* for the platform, the virtual machine may instead use some
* platform-specific minimum value; if the specified value is unreasonably
* high, the virtual machine may instead use some platform-specific
* maximum. Likewise, the virtual machine is free to round the specified
* value up or down as it sees fit (or to ignore it completely).
*
* <p>Specifying a value of zero for the {@code stackSize} parameter will
* cause this constructor to behave exactly like the
* {@code Thread(ThreadGroup, Runnable, String)} constructor.
*
* <p><i>Due to the platform-dependent nature of the behavior of this
* constructor, extreme care should be exercised in its use.
* The thread stack size necessary to perform a given computation will
* likely vary from one JRE implementation to another. In light of this
* variation, careful tuning of the stack size parameter may be required,
* and the tuning may need to be repeated for each JRE implementation on
* which an application is to run.</i>
*
* <p>Implementation note: Java platform implementers are encouraged to
* document their implementation's behavior with respect to the
* {@code stackSize} parameter.
*
* @param group the thread group. If {@code null} and there is a security
* manager, the group is determined by {@linkplain
* SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
* If there is not a security manager or {@code
* SecurityManager.getThreadGroup()} returns {@code null}, the group
* is set to the current thread's thread group.
* @param target the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this thread's run method is invoked.
* @param name the name of the new thread
* @param stackSize the desired stack size for the new thread, or zero to indicate
* that this parameter is to be ignored.
*
* @throws SecurityException if the current thread cannot create a thread in the specified
* thread group
* @since 1.4
*/
// ▶ 1-1
public Thread(ThreadGroup group, Runnable target, String name, long stackSize) {
this(group, target, name, stackSize, null, true);
}
/**
* Allocates a new {@code Thread} object so that it has {@code target}
* as its run object, has the specified {@code name} as its name,
* belongs to the thread group referred to by {@code group}, has
* the specified {@code stackSize}, and inherits initial values for
* {@linkplain InheritableThreadLocal inheritable thread-local} variables
* if {@code inheritThreadLocals} is {@code true}.
*
* <p> This constructor is identical to {@link
* #Thread(ThreadGroup, Runnable, String, long)} with the added ability to
* suppress, or not, the inheriting of initial values for inheritable
* thread-local variables from the constructing thread. This allows for
* finer grain control over inheritable thread-locals. Care must be taken
* when passing a value of {@code false} for {@code inheritThreadLocals},
* as it may lead to unexpected behavior if the new thread executes code
* that expects a specific thread-local value to be inherited.
*
* <p> Specifying a value of {@code true} for the {@code inheritThreadLocals}
* parameter will cause this constructor to behave exactly like the
* {@code Thread(ThreadGroup, Runnable, String, long)} constructor.
*
* @param group the thread group. If {@code null} and there is a security
* manager, the group is determined by {@linkplain
* SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
* If there is not a security manager or {@code
* SecurityManager.getThreadGroup()} returns {@code null}, the group
* is set to the current thread's thread group.
* @param target the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this thread's run method is invoked.
* @param name the name of the new thread
* @param stackSize the desired stack size for the new thread, or zero to indicate
* that this parameter is to be ignored
* @param inheritThreadLocals if {@code true}, inherit initial values for inheritable
* thread-locals from the constructing thread, otherwise no initial
* values are inherited
*
* @throws SecurityException if the current thread cannot create a thread in the specified
* thread group
* @since 9
*/
// ▶ 1-2
public Thread(ThreadGroup group, Runnable target, String name, long stackSize, boolean inheritThreadLocals) {
this(group, target, name, stackSize, null, inheritThreadLocals);
}
/**
* Creates a new Thread that inherits the given AccessControlContext
* but thread-local variables are not inherited.
* This is not a public constructor.
*/
// ▶ 1-3
Thread(Runnable target, AccessControlContext acc) {
this(null, target, "Thread-" + nextThreadNum(), 0, acc, false);
}
/**
* Initializes a Thread.
*
* @param g the Thread group
* @param target the object whose run() method gets called
* @param name the name of the new Thread
* @param stackSize the desired stack size for the new thread, or
* zero to indicate that this parameter is to be ignored.
* @param acc the AccessControlContext to inherit, or
* AccessController.getContext() if null
* @param inheritThreadLocals if {@code true}, inherit initial values for
* inheritable thread-locals from the constructing thread
*/
// ▶ 1
private Thread(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc, boolean inheritThreadLocals) {
// 线程必须有名称,没有主动设置的话就使用默认名称
if(name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name; // 线程名称
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if(g == null) {
/* Determine if it's an applet or not */
// If there is a security manager, ask the security manager what to do.
if(security != null) {
g = security.getThreadGroup();
}
// If the security manager doesn't have a strong opinion on the matter, use the parent thread group.
if(g == null) {
g = parent.getThreadGroup();
}
}
// checkAccess regardless of whether or not threadgroup is explicitly passed in.
g.checkAccess();
// Do we have the required permissions?
if(security != null) {
if(isCCLOverridden(getClass())) {
security.checkPermission(SecurityConstants.SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
// 将当前线程视为未启动线程,并在其线程组中计数
g.addUnstarted();
this.group = g; // 线程组
this.daemon = parent.isDaemon(); // 守护线程
this.priority = parent.getPriority(); // 线程优先级
if(security == null || isCCLOverridden(parent.getClass())) {
this.contextClassLoader = parent.getContextClassLoader();
} else {
this.contextClassLoader = parent.contextClassLoader;
}
this.inheritedAccessControlContext = acc != null ? acc : AccessController.getContext(); // 此线程继承的AccessControlContext
this.target = target; // 当前线程将要执行的动作
setPriority(priority);
// 如果需要继承父线程的键值对组合<ThreadLocal, Object>,且该键值对存在
if(inheritThreadLocals && parent.inheritableThreadLocals != null) {
// 创建新的map,并继承父线程的数据
this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
}
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
/* Set thread ID */
this.tid = nextThreadID();
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 获取线程 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a reference to the currently executing thread object.
*
* @return the currently executing thread.
*/
// 返回调用此方法的当前线程
@HotSpotIntrinsicCandidate
public static native Thread currentThread();
/*▲ 获取线程 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 线程属性 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns this thread's name.
*
* @return this thread's name.
*
* @see #setName(String)
*/
public final String getName() {
return name;
}
/**
* Changes the name of this thread to be equal to the argument {@code name}.
* <p>
* First the {@code checkAccess} method of this thread is called
* with no arguments. This may result in throwing a
* {@code SecurityException}.
*
* @param name the new name for this thread.
*
* @throws SecurityException if the current thread cannot modify this
* thread.
* @see #getName
* @see #checkAccess()
*/
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);
}
}
/**
* Returns the thread group to which this thread belongs.
* This method returns null if this thread has died
* (been stopped).
*
* @return this thread's thread group.
*/
public final ThreadGroup getThreadGroup() {
return group;
}
/**
* Tests if this thread is a daemon thread.
*
* @return {@code true} if this thread is a daemon thread;
* {@code false} otherwise.
*
* @see #setDaemon(boolean)
*/
// 返回true代表当前线程是守护线程
public final boolean isDaemon() {
return daemon;
}
/**
* Marks this thread as either a {@linkplain #isDaemon daemon} thread
* or a user thread. The Java Virtual Machine exits when the only
* threads running are all daemon threads.
*
* <p> This method must be invoked before the thread is started.
*
* @param on if {@code true}, marks this thread as a daemon thread
*
* @throws IllegalThreadStateException if this thread is {@linkplain #isAlive alive}
* @throws SecurityException if {@link #checkAccess} determines that the current
* thread cannot modify this thread
*/
// 设置当前线程为守护线程/非守护线程
public final void setDaemon(boolean on) {
checkAccess();
if(isAlive()) {
throw new IllegalThreadStateException();
}
daemon = on;
}
/**
* Returns this thread's priority.
*
* @return this thread's priority.
*
* @see #setPriority
*/
// 返回线程优先级
public final int getPriority() {
return priority;
}
/**
* Changes the priority of this thread.
* <p>
* First the {@code checkAccess} method of this thread is called
* with no arguments. This may result in throwing a {@code SecurityException}.
* <p>
* Otherwise, the priority of this thread is set to the smaller of
* the specified {@code newPriority} and the maximum permitted
* priority of the thread's thread group.
*
* @param newPriority priority to set this thread to
*
* @throws IllegalArgumentException If the priority is not in the
* range {@code MIN_PRIORITY} to
* {@code MAX_PRIORITY}.
* @throws SecurityException if the current thread cannot modify
* this thread.
* @see #getPriority
* @see #checkAccess()
* @see #getThreadGroup()
* @see #MAX_PRIORITY
* @see #MIN_PRIORITY
* @see ThreadGroup#getMaxPriority()
*/
// 设置线程优先级
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if(newPriority>MAX_PRIORITY || newPriority<MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if(newPriority>g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}
/**
* Returns the identifier of this Thread. The thread ID is a positive
* {@code long} number generated when this thread was created.
* The thread ID is unique and remains unchanged during its lifetime.
* When a thread is terminated, this thread ID may be reused.
*
* @return this thread's ID.
*
* @since 1.5
*/
// 获取线程ID
public long getId() {
return tid;
}
/**
* Returns the context {@code ClassLoader} for this thread. The context
* {@code ClassLoader} is provided by the creator of the thread for use
* by code running in this thread when loading classes and resources.
* If not {@linkplain #setContextClassLoader set}, the default is the
* {@code ClassLoader} context of the parent thread. The context
* {@code ClassLoader} of the
* primordial thread is typically set to the class loader used to load the
* application.
*
* @return the context {@code ClassLoader} for this thread, or {@code null}
* indicating the system class loader (or, failing that, the
* bootstrap class loader)
*
* @throws SecurityException if a security manager is present, and the caller's class loader
* is not {@code null} and is not the same as or an ancestor of the
* context class loader, and the caller does not have the
* {@link RuntimePermission}{@code ("getClassLoader")}
* @since 1.2
*/
// 获取当前线程上下文类加载器
@CallerSensitive
public ClassLoader getContextClassLoader() {
if(contextClassLoader == null) {
return null;
}
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
ClassLoader.checkClassLoaderPermission(contextClassLoader, Reflection.getCallerClass());
}
return contextClassLoader;
}
/**
* Sets the context ClassLoader for this Thread. The context
* ClassLoader can be set when a thread is created, and allows
* the creator of the thread to provide the appropriate class loader,
* through {@code getContextClassLoader}, to code running in the thread
* when loading classes and resources.
*
* <p>If a security manager is present, its {@link
* SecurityManager#checkPermission(java.security.Permission) checkPermission}
* method is invoked with a {@link RuntimePermission RuntimePermission}{@code
* ("setContextClassLoader")} permission to see if setting the context
* ClassLoader is permitted.
*
* @param cl the context ClassLoader for this Thread, or null indicating the
* system class loader (or, failing that, the bootstrap class loader)
*
* @throws SecurityException if the current thread cannot set the context ClassLoader
* @since 1.2
*/
// 设置线程上下文类加载器
public void setContextClassLoader(ClassLoader cl) {
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
sm.checkPermission(new RuntimePermission("setContextClassLoader"));
}
contextClassLoader = cl;
}
/* 以下方法用于构造器的默认行为 */
// 获取下一个线程编号,用于合成线程名
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
// 获取下一个线程ID
private static synchronized long nextThreadID() {
return ++threadSeqNumber;
}
/*▲ 线程属性 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 线程状态 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the {@code run} method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* {@code start} method) and the other thread (which executes its
* {@code run} method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @throws IllegalThreadStateException if the thread was already started.
* @see #run()
* @see #stop()
*/
// 启动线程,线程状态从NEW进入RUNNABLE
public synchronized void start() {
/*
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if(threadStatus != 0)
throw new IllegalThreadStateException();
/*
* Notify the group that this thread is about to be started so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented.
*/
// 将当前线程加入到所在的线程组,记录为活跃线程
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
// 线程启动失败,将其从线程组中删除,未启动线程数量重新加一
if(!started) {
group.threadStartFailed(this);
}
} catch(Throwable ignore) {
// do nothing. If start0 threw a Throwable then it will be passed up the call stack
}
}
}
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds, subject to
* the precision and accuracy of system timers and schedulers. The thread
* does not lose ownership of any monitors.
*
* @param millis the length of time to sleep in milliseconds
*
* @throws IllegalArgumentException if the value of {@code millis} is negative
* @throws InterruptedException if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
// 使线程进入TIMED_WAITING状态,millis毫秒后自己醒来(不释放锁)
public static native void sleep(long millis) throws InterruptedException;
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds plus the specified
* number of nanoseconds, subject to the precision and accuracy of system
* timers and schedulers. The thread does not lose ownership of any
* monitors.
*
* @param millis the length of time to sleep in milliseconds
* @param nanos {@code 0-999999} additional nanoseconds to sleep
*
* @throws IllegalArgumentException if the value of {@code millis} is negative, or the value of
* {@code nanos} is not in the range {@code 0-999999}
* @throws InterruptedException if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
/*
* 使线程进入TIMED_WAITING状态
* 至少等待millis毫秒,nanos是一个纳秒级的附加时间,用来微调millis参数(不释放锁)
*/
public static void sleep(long millis, int nanos) throws InterruptedException {
if(millis<0) {
throw new IllegalArgumentException("timeout value is negative");
}
// 纳秒值的取值在1毫秒之内
if(nanos<0 || nanos>999999) {
throw new IllegalArgumentException("nanosecond timeout value out of range");
}
// 类似四舍五入,近似到1毫秒
if(nanos >= 500000 || (nanos != 0 && millis == 0)) {
millis++;
}
sleep(millis);