[Java多线程]-Thread和Runable源码解析
多线程:(百度百科借一波定义)
多线程(英语:multithreading),是指从软件或者硬件上实现多个线程并发执行的技术。具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程,进而提升整体处理性能。具有这种能力的系统包括对称多处理机、多核心处理器以及芯片级多处理(Chip-level multithreading)或同时多线程(Simultaneous multithreading)处理器。 在一个程序中,这些独立运行的程序片段叫作“线程”(Thread),利用它编程的概念就叫作“多线程处理(Multithreading)”。具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程(台湾译作“执行绪”),进而提升整体处理性能。
两种实现方式:
继承Thread类:
1 public class Test2 extends Thread{
2 public void run() {
3 for (int i = 0; i < 5; i++) {
4 System.out.println(i);
5 }
6 }
7 public static void main(String[] args) {
8 Test2 t2 =new Test2();
9 t2.start();
10 for (int i = 0; i <5; i++) {
11 System.out.println("main.......");
12 }
13 }
14 }
实现Runable接口:
1 public class Test2_2 implements Runnable{
2 public void run() {
3 for (int i = 0; i < 5; i++) {
4 System.out.println(i);
5 }
6 }
7 public static void main(String[] args) {
8 Test2_2 t2 =new Test2_2();
9 new Thread(t2).start();
10 for (int i = 0; i <5; i++) {
11 System.out.println("main.......");
12 }
13 }
14 }
这两种方式都能实现一个线程,当我们启动一个test线程的的时候,实际上是启动了main和test两个线程。两个线程并行执行,所以 他们执行的顺序是不确定的,取决于谁先获得CPU资源。同时还有一个必定会启动的线程就是垃圾回收线程,程序运行在JVM上,启动线程就是启动程序,JVM需要对它进行资源分配和管理,而java的内存自动管理机制就会启动垃圾回收线程来管理资源。
Thread和Runable的异同:
挖一下他们的源码看看他们的内部构造:
Runable接口:如下,可以看到这个接口只有一个抽象方法Run().那么我们事先这个接口创建一个线程里面的属性和方法是哪里来的呢,后面会说到。
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
Thread类:由于类里面的东西比较多,需要看的可以打开看下,可以看到Thread实现了Runable接口,其中还拥有许多自己的属性和方法。
1 /*
2 * Copyright (c) 1994, 2016, Oracle and/or its affiliates. All rights reserved.
3 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
4 *
5 *
6 *
7 *
8 *
9 *
10 *
11 *
12 *
13 *
14 *
15 *
16 *
17 *
18 *
19 *
20 *
21 *
22 *
23 *
24 */
25
26 package java.lang;
27
28 import java.lang.ref.Reference;
29 import java.lang.ref.ReferenceQueue;
30 import java.lang.ref.WeakReference;
31 import java.security.AccessController;
32 import java.security.AccessControlContext;
33 import java.security.PrivilegedAction;
34 import java.util.Map;
35 import java.util.HashMap;
36 import java.util.concurrent.ConcurrentHashMap;
37 import java.util.concurrent.ConcurrentMap;
38 import java.util.concurrent.locks.LockSupport;
39 import sun.nio.ch.Interruptible;
40 import sun.reflect.CallerSensitive;
41 import sun.reflect.Reflection;
42 import sun.security.util.SecurityConstants;
43
44
45 /**
46 * A <i>thread</i> is a thread of execution in a program. The Java
47 * Virtual Machine allows an application to have multiple threads of
48 * execution running concurrently.
49 * <p>
50 * Every thread has a priority. Threads with higher priority are
51 * executed in preference to threads with lower priority. Each thread
52 * may or may not also be marked as a daemon. When code running in
53 * some thread creates a new <code>Thread</code> object, the new
54 * thread has its priority initially set equal to the priority of the
55 * creating thread, and is a daemon thread if and only if the
56 * creating thread is a daemon.
57 * <p>
58 * When a Java Virtual Machine starts up, there is usually a single
59 * non-daemon thread (which typically calls the method named
60 * <code>main</code> of some designated class). The Java Virtual
61 * Machine continues to execute threads until either of the following
62 * occurs:
63 * <ul>
64 * <li>The <code>exit</code> method of class <code>Runtime</code> has been
65 * called and the security manager has permitted the exit operation
66 * to take place.
67 * <li>All threads that are not daemon threads have died, either by
68 * returning from the call to the <code>run</code> method or by
69 * throwing an exception that propagates beyond the <code>run</code>
70 * method.
71 * </ul>
72 * <p>
73 * There are two ways to create a new thread of execution. One is to
74 * declare a class to be a subclass of <code>Thread</code>. This
75 * subclass should override the <code>run</code> method of class
76 * <code>Thread</code>. An instance of the subclass can then be
77 * allocated and started. For example, a thread that computes primes
78 * larger than a stated value could be written as follows:
79 * <hr><blockquote><pre>
80 * class PrimeThread extends Thread {
81 * long minPrime;
82 * PrimeThread(long minPrime) {
83 * this.minPrime = minPrime;
84 * }
85 *
86 * public void run() {
87 * // compute primes larger than minPrime
88 * . . .
89 * }
90 * }
91 * </pre></blockquote><hr>
92 * <p>
93 * The following code would then create a thread and start it running:
94 * <blockquote><pre>
95 * PrimeThread p = new PrimeThread(143);
96 * p.start();
97 * </pre></blockquote>
98 * <p>
99 * The other way to create a thread is to declare a class that
100 * implements the <code>Runnable</code> interface. That class then
101 * implements the <code>run</code> method. An instance of the class can
102 * then be allocated, passed as an argument when creating
103 * <code>Thread</code>, and started. The same example in this other
104 * style looks like the following:
105 * <hr><blockquote><pre>
106 * class PrimeRun implements Runnable {
107 * long minPrime;
108 * PrimeRun(long minPrime) {
109 * this.minPrime = minPrime;
110 * }
111 *
112 * public void run() {
113 * // compute primes larger than minPrime
114 * . . .
115 * }
116 * }
117 * </pre></blockquote><hr>
118 * <p>
119 * The following code would then create a thread and start it running:
120 * <blockquote><pre>
121 * PrimeRun p = new PrimeRun(143);
122 * new Thread(p).start();
123 * </pre></blockquote>
124 * <p>
125 * Every thread has a name for identification purposes. More than
126 * one thread may have the same name. If a name is not specified when
127 * a thread is created, a new name is generated for it.
128 * <p>
129 * Unless otherwise noted, passing a {@code null} argument to a constructor
130 * or method in this class will cause a {@link NullPointerException} to be
131 * thrown.
132 *
133 * @author unascribed
134 * @see Runnable
135 * @see Runtime#exit(int)
136 * @see #run()
137 * @see #stop()
138 * @since JDK1.0
139 */
140 public
141 class Thread implements Runnable {
142 /* Make sure registerNatives is the first thing <clinit> does. */
143 private static native void registerNatives();
144 static {
145 registerNatives();
146 }
147
148 private volatile String name;
149 private int priority;
150 private Thread threadQ;
151 private long eetop;
152
153 /* Whether or not to single_step this thread. */
154 private boolean single_step;
155
156 /* Whether or not the thread is a daemon thread. */
157 private boolean daemon = false;
158
159 /* JVM state */
160 private boolean stillborn = false;
161
162 /* What will be run. */
163 private Runnable target;
164
165 /* The group of this thread */
166 private ThreadGroup group;
167
168 /* The context ClassLoader for this thread */
169 private ClassLoader contextClassLoader;
170
171 /* The inherited AccessControlContext of this thread */
172 private AccessControlContext inheritedAccessControlContext;
173
174 /* For autonumbering anonymous threads. */
175 private static int threadInitNumber;
176 private static synchronized int nextThreadNum() {
177 return threadInitNumber++;
178 }
179
180 /* ThreadLocal values pertaining to this thread. This map is maintained
181 * by the ThreadLocal class. */
182 ThreadLocal.ThreadLocalMap threadLocals = null;
183
184 /*
185 * InheritableThreadLocal values pertaining to this thread. This map is
186 * maintained by the InheritableThreadLocal class.
187 */
188 ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
189
190 /*
191 * The requested stack size for this thread, or 0 if the creator did
192 * not specify a stack size. It is up to the VM to do whatever it
193 * likes with this number; some VMs will ignore it.
194 */
195 private long stackSize;
196
197 /*
198 * JVM-private state that persists after native thread termination.
199 */
200 private long nativeParkEventPointer;
201
202 /*
203 * Thread ID
204 */
205 private long tid;
206
207 /* For generating thread ID */
208 private static long threadSeqNumber;
209
210 /* Java thread status for tools,
211 * initialized to indicate thread 'not yet started'
212 */
213
214 private volatile int threadStatus = 0;
215
216
217 private static synchronized long nextThreadID() {
218 return ++threadSeqNumber;
219 }
220
221 /**
222 * The argument supplied to the current call to
223 * java.util.concurrent.locks.LockSupport.park.
224 * Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
225 * Accessed using java.util.concurrent.locks.LockSupport.getBlocker
226 */
227 volatile Object parkBlocker;
228
229 /* The object in which this thread is blocked in an interruptible I/O
230 * operation, if any. The blocker's interrupt method should be invoked
231 * after setting this thread's interrupt status.
232 */
233 private volatile Interruptible blocker;
234 private final Object blockerLock = new Object();
235
236 /* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code
237 */
238 void blockedOn(Interruptible b) {
239 synchronized (blockerLock) {
240 blocker = b;
241 }
242 }
243
244 /**
245 * The minimum priority that a thread can have.
246 */
247 public final static int MIN_PRIORITY = 1;
248
249 /**
250 * The default priority that is assigned to a thread.
251 */
252 public final static int NORM_PRIORITY = 5;
253
254 /**
255 * The maximum priority that a thread can have.
256 */
257 public final static int MAX_PRIORITY = 10;
258
259 /**
260 * Returns a reference to the currently executing thread object.
261 *
262 * @return the currently executing thread.
263 */
264 public static native Thread currentThread();
265
266 /**
267 * A hint to the scheduler that the current thread is willing to yield
268 * its current use of a processor. The scheduler is free to ignore this
269 * hint.
270 *
271 * <p> Yield is a heuristic attempt to improve relative progression
272 * between threads that would otherwise over-utilise a CPU. Its use
273 * should be combined with detailed profiling and benchmarking to
274 * ensure that it actually has the desired effect.
275 *
276 * <p> It is rarely appropriate to use this method. It may be useful
277 * for debugging or testing purposes, where it may help to reproduce
278 * bugs due to race conditions. It may also be useful when designing
279 * concurrency control constructs such as the ones in the
280 * {@link java.util.concurrent.locks} package.
281 */
282 public static native void yield();
283
284 /**
285 * Causes the currently executing thread to sleep (temporarily cease
286 * execution) for the specified number of milliseconds, subject to
287 * the precision and accuracy of system timers and schedulers. The thread
288 * does not lose ownership of any monitors.
289 *
290 * @param millis
291 * the length of time to sleep in milliseconds
292 *
293 * @throws IllegalArgumentException
294 * if the value of {@code millis} is negative
295 *
296 * @throws InterruptedException
297 * if any thread has interrupted the current thread. The
298 * <i>interrupted status</i> of the current thread is
299 * cleared when this exception is thrown.
300 */
301 public static native void sleep(long millis) throws InterruptedException;
302
303 /**
304 * Causes the currently executing thread to sleep (temporarily cease
305 * execution) for the specified number of milliseconds plus the specified
306 * number of nanoseconds, subject to the precision and accuracy of system
307 * timers and schedulers. The thread does not lose ownership of any
308 * monitors.
309 *
310 * @param millis
311 * the length of time to sleep in milliseconds
312 *
313 * @param nanos
314 * {@code 0-999999} additional nanoseconds to sleep
315 *
316 * @throws IllegalArgumentException
317 * if the value of {@code millis} is negative, or the value of
318 * {@code nanos} is not in the range {@code 0-999999}
319 *
320 * @throws InterruptedException
321 * if any thread has interrupted the current thread. The
322 * <i>interrupted status</i> of the current thread is
323 * cleared when this exception is thrown.
324 */
325 public static void sleep(long millis, int nanos)
326 throws InterruptedException {
327 if (millis < 0) {
328 throw new IllegalArgumentException("timeout value is negative");
329 }
330
331 if (nanos < 0 || nanos > 999999) {
332 throw new IllegalArgumentException(
333 "nanosecond timeout value out of range");
334 }
335
336 if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
337 millis++;
338 }
339
340 sleep(millis);
341 }
342
343 /**
344 * Initializes a Thread with the current AccessControlContext.
345 * @see #init(ThreadGroup,Runnable,String,long,AccessControlContext)
346 */
347 private void init(ThreadGroup g, Runnable target, String name,
348 long stackSize) {
349 init(g, target, name, stackSize, null);
350 }
351
352 /**
353 * Initializes a Thread.
354 *
355 * @param g the Thread group
356 * @param target the object whose run() method gets called
357 * @param name the name of the new Thread
358 * @param stackSize the desired stack size for the new thread, or
359 * zero to indicate that this parameter is to be ignored.
360 * @param acc the AccessControlContext to inherit, or
361 * AccessController.getContext() if null
362 */
363 private void init(ThreadGroup g, Runnable target, String name,
364 long stackSize, AccessControlContext acc) {
365 if (name == null) {
366 throw new NullPointerException("name cannot be null");
367 }
368
369 this.name = name;
370
371 Thread parent = currentThread();
372 SecurityManager security = System.getSecurityManager();
373 if (g == null) {
374 /* Determine if it's an applet or not */
375
376 /* If there is a security manager, ask the security manager
377 what to do. */
378 if (security != null) {
379 g = security.getThreadGroup();
380 }
381
382 /* If the security doesn't have a strong opinion of the matter
383 use the parent thread group. */
384 if (g == null) {
385 g = parent.getThreadGroup();
386 }
387 }
388
389 /* checkAccess regardless of whether or not threadgroup is
390 explicitly passed in. */
391 g.checkAccess();
392
393 /*
394 * Do we have the required permissions?
395 */
396 if (security != null) {
397 if (isCCLOverridden(getClass())) {
398 security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
399 }
400 }
401
402 g.addUnstarted();
403
404 this.group = g;
405 this.daemon = parent.isDaemon();
406 this.priority = parent.getPriority();
407 if (security == null || isCCLOverridden(parent.getClass()))
408 this.contextClassLoader = parent.getContextClassLoader();
409 else
410 this.contextClassLoader = parent.contextClassLoader;
411 this.inheritedAccessControlContext =
412 acc != null ? acc : AccessController.getContext();
413 this.target = target;
414 setPriority(priority);
415 if (parent.inheritableThreadLocals != null)
416 this.inheritableThreadLocals =
417 ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
418 /* Stash the specified stack size in case the VM cares */
419 this.stackSize = stackSize;
420
421 /* Set thread ID */
422 tid = nextThreadID();
423 }
424
425 /**
426 * Throws CloneNotSupportedException as a Thread can not be meaningfully
427 * cloned. Construct a new Thread instead.
428 *
429 * @throws CloneNotSupportedException
430 * always
431 */
432 @Override
433 protected Object clone() throws CloneNotSupportedException {
434 throw new CloneNotSupportedException();
435 }
436
437 /**
438 * Allocates a new {@code Thread} object. This constructor has the same
439 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
440 * {@code (null, null, gname)}, where {@code gname} is a newly generated
441 * name. Automatically generated names are of the form
442 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
443 */
444 public Thread() {
445 init(null, null, "Thread-" + nextThreadNum(), 0);
446 }
447
448 /**
449 * Allocates a new {@code Thread} object. This constructor has the same
450 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
451 * {@code (null, target, gname)}, where {@code gname} is a newly generated
452 * name. Automatically generated names are of the form
453 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
454 *
455 * @param target
456 * the object whose {@code run} method is invoked when this thread
457 * is started. If {@code null}, this classes {@code run} method does
458 * nothing.
459 */
460 public Thread(Runnable target) {
461 init(null, target, "Thread-" + nextThreadNum(), 0);
462 }
463
464 /**
465 * Creates a new Thread that inherits the given AccessControlContext.
466 * This is not a public constructor.
467 */
468 Thread(Runnable target, AccessControlContext acc) {
469 init(null, target, "Thread-" + nextThreadNum(), 0, acc);
470 }
471
472 /**
473 * Allocates a new {@code Thread} object. This constructor has the same
474 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
475 * {@code (group, target, gname)} ,where {@code gname} is a newly generated
476 * name. Automatically generated names are of the form
477 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
478 *
479 * @param group
480 * the thread group. If {@code null} and there is a security
481 * manager, the group is determined by {@linkplain
482 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
483 * If there is not a security manager or {@code
484 * SecurityManager.getThreadGroup()} returns {@code null}, the group
485 * is set to the current thread's thread group.
486 *
487 * @param target
488 * the object whose {@code run} method is invoked when this thread
489 * is started. If {@code null}, this thread's run method is invoked.
490 *
491 * @throws SecurityException
492 * if the current thread cannot create a thread in the specified
493 * thread group
494 */
495 public Thread(ThreadGroup group, Runnable target) {
496 init(group, target, "Thread-" + nextThreadNum(), 0);
497 }
498
499 /**
500 * Allocates a new {@code Thread} object. This constructor has the same
501 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
502 * {@code (null, null, name)}.
503 *
504 * @param name
505 * the name of the new thread
506 */
507 public Thread(String name) {
508 init(null, null, name, 0);
509 }
510
511 /**
512 * Allocates a new {@code Thread} object. This constructor has the same
513 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
514 * {@code (group, null, name)}.
515 *
516 * @param group
517 * the thread group. If {@code null} and there is a security
518 * manager, the group is determined by {@linkplain
519 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
520 * If there is not a security manager or {@code
521 * SecurityManager.getThreadGroup()} returns {@code null}, the group
522 * is set to the current thread's thread group.
523 *
524 * @param name
525 * the name of the new thread
526 *
527 * @throws SecurityException
528 * if the current thread cannot create a thread in the specified
529 * thread group
530 */
531 public Thread(ThreadGroup group, String name) {
532 init(group, null, name, 0);
533 }
534
535 /**
536 * Allocates a new {@code Thread} object. This constructor has the same
537 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
538 * {@code (null, target, name)}.
539 *
540 * @param target
541 * the object whose {@code run} method is invoked when this thread
542 * is started. If {@code null}, this thread's run method is invoked.
543 *
544 * @param name
545 * the name of the new thread
546 */
547 public Thread(Runnable target, String name) {
548 init(null, target, name, 0);
549 }
550
551 /**
552 * Allocates a new {@code Thread} object so that it has {@code target}
553 * as its run object, has the specified {@code name} as its name,
554 * and belongs to the thread group referred to by {@code group}.
555 *
556 * <p>If there is a security manager, its
557 * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
558 * method is invoked with the ThreadGroup as its argument.
559 *
560 * <p>In addition, its {@code checkPermission} method is invoked with
561 * the {@code RuntimePermission("enableContextClassLoaderOverride")}
562 * permission when invoked directly or indirectly by the constructor
563 * of a subclass which overrides the {@code getContextClassLoader}
564 * or {@code setContextClassLoader} methods.
565 *
566 * <p>The priority of the newly created thread is set equal to the
567 * priority of the thread creating it, that is, the currently running
568 * thread. The method {@linkplain #setPriority setPriority} may be
569 * used to change the priority to a new value.
570 *
571 * <p>The newly created thread is initially marked as being a daemon
572 * thread if and only if the thread creating it is currently marked
573 * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
574 * may be used to change whether or not a thread is a daemon.
575 *
576 * @param group
577 * the thread group. If {@code null} and there is a security
578 * manager, the group is determined by {@linkplain
579 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
580 * If there is not a security manager or {@code
581 * SecurityManager.getThreadGroup()} returns {@code null}, the group
582 * is set to the current thread's thread group.
583 *
584 * @param target
585 * the object whose {@code run} method is invoked when this thread
586 * is started. If {@code null}, this thread's run method is invoked.
587 *
588 * @param name
589 * the name of the new thread
590 *
591 * @throws SecurityException
592 * if the current thread cannot create a thread in the specified
593 * thread group or cannot override the context class loader methods.
594 */
595 public Thread(ThreadGroup group, Runnable target, String name) {
596 init(group, target, name, 0);
597 }
598
599 /**
600 * Allocates a new {@code Thread} object so that it has {@code target}
601 * as its run object, has the specified {@code name} as its name,
602 * and belongs to the thread group referred to by {@code group}, and has
603 * the specified <i>stack size</i>.
604 *
605 * <p>This constructor is identical to {@link
606 * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
607 * that it allows the thread stack size to be specified. The stack size
608 * is the approximate number of bytes of address space that the virtual
609 * machine is to allocate for this thread's stack. <b>The effect of the
610 * {@code stackSize} parameter, if any, is highly platform dependent.</b>
611 *
612 * <p>On some platforms, specifying a higher value for the
613 * {@code stackSize} parameter may allow a thread to achieve greater
614 * recursion depth before throwing a {@link StackOverflowError}.
615 * Similarly, specifying a lower value may allow a greater number of
616 * threads to exist concurrently without throwing an {@link
617 * OutOfMemoryError} (or other internal error). The details of
618 * the relationship between the value of the <tt>stackSize</tt> parameter
619 * and the maximum recursion depth and concurrency level are
620 * platform-dependent. <b>On some platforms, the value of the
621 * {@code stackSize} parameter may have no effect whatsoever.</b>
622 *
623 * <p>The virtual machine is free to treat the {@code stackSize}
624 * parameter as a suggestion. If the specified value is unreasonably low
625 * for the platform, the virtual machine may instead use some
626 * platform-specific minimum value; if the specified value is unreasonably
627 * high, the virtual machine may instead use some platform-specific
628 * maximum. Likewise, the virtual machine is free to round the specified
629 * value up or down as it sees fit (or to ignore it completely).
630 *
631 * <p>Specifying a value of zero for the {@code stackSize} parameter will
632 * cause this constructor to behave exactly like the
633 * {@code Thread(ThreadGroup, Runnable, String)} constructor.
634 *
635 * <p><i>Due to the platform-dependent nature of the behavior of this
636 * constructor, extreme care should be exercised in its use.
637 * The thread stack size necessary to perform a given computation will
638 * likely vary from one JRE implementation to another. In light of this
639 * variation, careful tuning of the stack size parameter may be required,
640 * and the tuning may need to be repeated for each JRE implementation on
641 * which an application is to run.</i>
642 *
643 * <p>Implementation note: Java platform implementers are encouraged to
644 * document their implementation's behavior with respect to the
645 * {@code stackSize} parameter.
646 *
647 *
648 * @param group
649 * the thread group. If {@code null} and there is a security
650 * manager, the group is determined by {@linkplain
651 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
652 * If there is not a security manager or {@code
653 * SecurityManager.getThreadGroup()} returns {@code null}, the group
654 * is set to the current thread's thread group.
655 *
656 * @param target
657 * the object whose {@code run} method is invoked when this thread
658 * is started. If {@code null}, this thread's run method is invoked.
659 *
660 * @param name
661 * the name of the new thread
662 *
663 * @param stackSize
664 * the desired stack size for the new thread, or zero to indicate
665 * that this parameter is to be ignored.
666 *
667 * @throws SecurityException
668 * if the current thread cannot create a thread in the specified
669 * thread group
670 *
671 * @since 1.4
672 */
673 public Thread(ThreadGroup group, Runnable target, String name,
674 long stackSize) {
675 init(group, target, name, stackSize);
676 }
677
678 /**
679 * Causes this thread to begin execution; the Java Virtual Machine
680 * calls the <code>run</code> method of this thread.
681 * <p>
682 * The result is that two threads are running concurrently: the
683 * current thread (which returns from the call to the
684 * <code>start</code> method) and the other thread (which executes its
685 * <code>run</code> method).
686 * <p>
687 * It is never legal to start a thread more than once.
688 * In particular, a thread may not be restarted once it has completed
689 * execution.
690 *
691 * @exception IllegalThreadStateException if the thread was already
692 * started.
693 * @see #run()
694 * @see #stop()
695 */
696 public synchronized void start() {
697 /**
698 * This method is not invoked for the main method thread or "system"
699 * group threads created/set up by the VM. Any new functionality added
700 * to this method in the future may have to also be added to the VM.
701 *
702 * A zero status value corresponds to state "NEW".
703 */
704 if (threadStatus != 0)
705 throw new IllegalThreadStateException();
706
707 /* Notify the group that this thread is about to be started
708 * so that it can be added to the group's list of threads
709 * and the group's unstarted count can be decremented. */
710 group.add(this);
711
712 boolean started = false;
713 try {
714 start0();
715 started = true;
716 } finally {
717 try {
718 if (!started) {
719 group.threadStartFailed(this);
720 }
721 } catch (Throwable ignore) {
722 /* do nothing. If start0 threw a Throwable then
723 it will be passed up the call stack */
724 }
725 }
726 }
727
728 private native void start0();
729
730 /**
731 * If this thread was constructed using a separate
732 * <code>Runnable</code> run object, then that
733 * <code>Runnable</code> object's <code>run</code> method is called;
734 * otherwise, this method does nothing and returns.
735 * <p>
736 * Subclasses of <code>Thread</code> should override this method.
737 *
738 * @see #start()
739 * @see #stop()
740 * @see #Thread(ThreadGroup, Runnable, String)
741 */
742 @Override
743 public void run() {
744 if (target != null) {
745 target.run();
746 }
747 }
748
749 /**
750 * This method is called by the system to give a Thread
751 * a chance to clean up before it actually exits.
752 */
753 private void exit() {
754 if (group != null) {
755 group.threadTerminated(this);
756 group = null;
757 }
758 /* Aggressively null out all reference fields: see bug 4006245 */
759 target = null;
760 /* Speed the release of some of these resources */
761 threadLocals = null;
762 inheritableThreadLocals = null;
763 inheritedAccessControlContext = null;
764 blocker = null;
765 uncaughtExceptionHandler = null;
766 }
767
768 /**
769 * Forces the thread to stop executing.
770 * <p>
771 * If there is a security manager installed, its <code>checkAccess</code>
772 * method is called with <code>this</code>
773 * as its argument. This may result in a
774 * <code>SecurityException</code> being raised (in the current thread).
775 * <p>
776 * If this thread is different from the current thread (that is, the current
777 * thread is trying to stop a thread other than itself), the
778 * security manager's <code>checkPermission</code> method (with a
779 * <code>RuntimePermission("stopThread")</code> argument) is called in
780 * addition.
781 * Again, this may result in throwing a
782 * <code>SecurityException</code> (in the current thread).
783 * <p>
784 * The thread represented by this thread is forced to stop whatever
785 * it is doing abnormally and to throw a newly created
786 * <code>ThreadDeath</code> object as an exception.
787 * <p>
788 * It is permitted to stop a thread that has not yet been started.
789 * If the thread is eventually started, it immediately terminates.
790 * <p>
791 * An application should not normally try to catch
792 * <code>ThreadDeath</code> unless it must do some extraordinary
793 * cleanup operation (note that the throwing of
794 * <code>ThreadDeath</code> causes <code>finally</code> clauses of
795 * <code>try</code> statements to be executed before the thread
796 * officially dies). If a <code>catch</code> clause catches a
797 * <code>ThreadDeath</code> object, it is important to rethrow the
798 * object so that the thread actually dies.
799 * <p>
800 * The top-level error handler that reacts to otherwise uncaught
801 * exceptions does not print out a message or otherwise notify the
802 * application if the uncaught exception is an instance of
803 * <code>ThreadDeath</code>.
804 *
805 * @exception SecurityException if the current thread cannot
806 * modify this thread.
807 * @see #interrupt()
808 * @see #checkAccess()
809 * @see #run()
810 * @see #start()
811 * @see ThreadDeath
812 * @see ThreadGroup#uncaughtException(Thread,Throwable)
813 * @see SecurityManager#checkAccess(Thread)
814 * @see SecurityManager#checkPermission
815 * @deprecated This method is inherently unsafe. Stopping a thread with
816 * Thread.stop causes it to unlock all of the monitors that it
817 * has locked (as a natural consequence of the unchecked
818 * <code>ThreadDeath</code> exception propagating up the stack). If
819 * any of the objects previously protected by these monitors were in
820 * an inconsistent state, the damaged objects become visible to
821 * other threads, potentially resulting in arbitrary behavior. Many
822 * uses of <code>stop</code> should be replaced by code that simply
823 * modifies some variable to indicate that the target thread should
824 * stop running. The target thread should check this variable
825 * regularly, and return from its run method in an orderly fashion
826 * if the variable indicates that it is to stop running. If the
827 * target thread waits for long periods (on a condition variable,
828 * for example), the <code>interrupt</code> method should be used to
829 * interrupt the wait.
830 * For more information, see
831 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
832 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
833 */
834 @Deprecated
835 public final void stop() {
836 SecurityManager security = System.getSecurityManager();
837 if (security != null) {
838 checkAccess();
839 if (this != Thread.currentThread()) {
840 security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
841 }
842 }
843 // A zero status value corresponds to "NEW", it can't change to
844 // not-NEW because we hold the lock.
845 if (threadStatus != 0) {
846 resume(); // Wake up thread if it was suspended; no-op otherwise
847 }
848
849 // The VM can handle all thread states
850 stop0(new ThreadDeath());
851 }
852
853 /**
854 * Throws {@code UnsupportedOperationException}.
855 *
856 * @param obj ignored
857 *
858 * @deprecated This method was originally designed to force a thread to stop
859 * and throw a given {@code Throwable} as an exception. It was
860 * inherently unsafe (see {@link #stop()} for details), and furthermore
861 * could be used to generate exceptions that the target thread was
862 * not prepared to handle.
863 * For more information, see
864 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
865 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
866 */
867 @Deprecated
868 public final synchronized void stop(Throwable obj) {
869 throw new UnsupportedOperationException();
870 }
871
872 /**
873 * Interrupts this thread.
874 *
875 * <p> Unless the current thread is interrupting itself, which is
876 * always permitted, the {@link #checkAccess() checkAccess} method
877 * of this thread is invoked, which may cause a {@link
878 * SecurityException} to be thrown.
879 *
880 * <p> If this thread is blocked in an invocation of the {@link
881 * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
882 * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
883 * class, or of the {@link #join()}, {@link #join(long)}, {@link
884 * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
885 * methods of this class, then its interrupt status will be cleared and it
886 * will receive an {@link InterruptedException}.
887 *
888 * <p> If this thread is blocked in an I/O operation upon an {@link
889 * java.nio.channels.InterruptibleChannel InterruptibleChannel}
890 * then the channel will be closed, the thread's interrupt
891 * status will be set, and the thread will receive a {@link
892 * java.nio.channels.ClosedByInterruptException}.
893 *
894 * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
895 * then the thread's interrupt status will be set and it will return
896 * immediately from the selection operation, possibly with a non-zero
897 * value, just as if the selector's {@link
898 * java.nio.channels.Selector#wakeup wakeup} method were invoked.
899 *
900 * <p> If none of the previous conditions hold then this thread's interrupt
901 * status will be set. </p>
902 *
903 * <p> Interrupting a thread that is not alive need not have any effect.
904 *
905 * @throws SecurityException
906 * if the current thread cannot modify this thread
907 *
908 * @revised 6.0
909 * @spec JSR-51
910 */
911 public void interrupt() {
912 if (this != Thread.currentThread())
913 checkAccess();
914
915 synchronized (blockerLock) {
916 Interruptible b = blocker;
917 if (b != null) {
918 interrupt0(); // Just to set the interrupt flag
919 b.interrupt(this);
920 return;
921 }
922 }
923 interrupt0();
924 }
925
926 /**
927 * Tests whether the current thread has been interrupted. The
928 * <i>interrupted status</i> of the thread is cleared by this method. In
929 * other words, if this method were to be called twice in succession, the
930 * second call would return false (unless the current thread were
931 * interrupted again, after the first call had cleared its interrupted
932 * status and before the second call had examined it).
933 *
934 * <p>A thread interruption ignored because a thread was not alive
935 * at the time of the interrupt will be reflected by this method
936 * returning false.
937 *
938 * @return <code>true</code> if the current thread has been interrupted;
939 * <code>false</code> otherwise.
940 * @see #isInterrupted()
941 * @revised 6.0
942 */
943 public static boolean interrupted() {
944 return currentThread().isInterrupted(true);
945 }
946
947 /**
948 * Tests whether this thread has been interrupted. The <i>interrupted
949 * status</i> of the thread is unaffected by this method.
950 *
951 * <p>A thread interruption ignored because a thread was not alive
952 * at the time of the interrupt will be reflected by this method
953 * returning false.
954 *
955 * @return <code>true</code> if this thread has been interrupted;
956 * <code>false</code> otherwise.
957 * @see #interrupted()
958 * @revised 6.0
959 */
960 public boolean isInterrupted() {
961 return isInterrupted(false);
962 }
963
964 /**
965 * Tests if some Thread has been interrupted. The interrupted state
966 * is reset or not based on the value of ClearInterrupted that is
967 * passed.
968 */
969 private native boolean isInterrupted(boolean ClearInterrupted);
970
971 /**
972 * Throws {@link NoSuchMethodError}.
973 *
974 * @deprecated This method was originally designed to destroy this
975 * thread without any cleanup. Any monitors it held would have
976 * remained locked. However, the method was never implemented.
977 * If if were to be implemented, it would be deadlock-prone in
978 * much the manner of {@link #suspend}. If the target thread held
979 * a lock protecting a critical system resource when it was
980 * destroyed, no thread could ever access this resource again.
981 * If another thread ever attempted to lock this resource, deadlock
982 * would result. Such deadlocks typically manifest themselves as
983 * "frozen" processes. For more information, see
984 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">
985 * Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
986 * @throws NoSuchMethodError always
987 */
988 @Deprecated
989 public void destroy() {
990 throw new NoSuchMethodError();
991 }
992
993 /**
994 * Tests if this thread is alive. A thread is alive if it has
995 * been started and has not yet died.
996 *
997 * @return <code>true</code> if this thread is alive;
998 * <code>false</code> otherwise.
999 */
1000 public final native boolean isAlive();
1001
1002 /**
1003 * Suspends this thread.
1004 * <p>
1005 * First, the <code>checkAccess</code> method of this thread is called
1006 * with no arguments. This may result in throwing a
1007 * <code>SecurityException </code>(in the current thread).
1008 * <p>
1009 * If the thread is alive, it is suspended and makes no further
1010 * progress unless and until it is resumed.
1011 *
1012 * @exception SecurityException if the current thread cannot modify
1013 * this thread.
1014 * @see #checkAccess
1015 * @deprecated This method has been deprecated, as it is
1016 * inherently deadlock-prone. If the target thread holds a lock on the
1017 * monitor protecting a critical system resource when it is suspended, no
1018 * thread can access this resource until the target thread is resumed. If
1019 * the thread that would resume the target thread attempts to lock this
1020 * monitor prior to calling <code>resume</code>, deadlock results. Such
1021 * deadlocks typically manifest themselves as "frozen" processes.
1022 * For more information, see
1023 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
1024 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1025 */
1026 @Deprecated
1027 public final void suspend() {
1028 checkAccess();
1029 suspend0();
1030 }
1031
1032 /**
1033 * Resumes a suspended thread.
1034 * <p>
1035 * First, the <code>checkAccess</code> method of this thread is called
1036 * with no arguments. This may result in throwing a
1037 * <code>SecurityException</code> (in the current thread).
1038 * <p>
1039 * If the thread is alive but suspended, it is resumed and is
1040 * permitted to make progress in its execution.
1041 *
1042 * @exception SecurityException if the current thread cannot modify this
1043 * thread.
1044 * @see #checkAccess
1045 * @see #suspend()
1046 * @deprecated This method exists solely for use with {@link #suspend},
1047 * which has been deprecated because it is deadlock-prone.
1048 * For more information, see
1049 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
1050 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
1051 */
1052 @Deprecated
1053 public final void resume() {
1054 checkAccess();
1055 resume0();
1056 }
1057
1058 /**
1059 * Changes the priority of this thread.
1060 * <p>
1061 * First the <code>checkAccess</code> method of this thread is called
1062 * with no arguments. This may result in throwing a
1063 * <code>SecurityException</code>.
1064 * <p>
1065 * Otherwise, the priority of this thread is set to the smaller of
1066 * the specified <code>newPriority</code> and the maximum permitted
1067 * priority of the thread's thread group.
1068 *
1069 * @param newPriority priority to set this thread to
1070 * @exception IllegalArgumentException If the priority is not in the
1071 * range <code>MIN_PRIORITY</code> to
1072 * <code>MAX_PRIORITY</code>.
1073 * @exception SecurityException if the current thread cannot modify
1074 * this thread.
1075 * @see #getPriority
1076 * @see #checkAccess()
1077 * @see #getThreadGroup()
1078 * @see #MAX_PRIORITY
1079 * @see #MIN_PRIORITY
1080 * @see ThreadGroup#getMaxPriority()
1081 */
1082 public final void setPriority(int newPriority) {
1083 ThreadGroup g;
1084 checkAccess();
1085 if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
1086 throw new IllegalArgumentException();
1087 }
1088 if((g = getThreadGroup()) != null) {
1089 if (newPriority > g.getMaxPriority()) {
1090 newPriority = g.getMaxPriority();
1091 }
1092 setPriority0(priority = newPriority);
1093 }
1094 }
1095
1096 /**
1097 * Returns this thread's priority.
1098 *
1099 * @return this thread's priority.
1100 * @see #setPriority
1101 */
1102 public final int getPriority() {
1103 return priority;
1104 }
1105
1106 /**
1107 * Changes the name of this thread to be equal to the argument
1108 * <code>name</code>.
1109 * <p>
1110 * First the <code>checkAccess</code> method of this thread is called
1111 * with no arguments. This may result in throwing a
1112 * <code>SecurityException</code>.
1113 *
1114 * @param name the new name for this thread.
1115 * @exception SecurityException if the current thread cannot modify this
1116 * thread.
1117 * @see #getName
1118 * @see #checkAccess()
1119 */
1120 public final synchronized void setName(String name) {
1121 checkAccess();
1122 if (name == null) {
1123 throw new NullPointerException("name cannot be null");
1124 }
1125
1126 this.name = name;
1127 if (threadStatus != 0) {
1128 setNativeName(name);
1129 }
1130 }
1131
1132 /**
1133 * Returns this thread's name.
1134 *
1135 * @return this thread's name.
1136 * @see #setName(String)
1137 */
1138 public final String getName() {
1139 return name;
1140 }
1141
1142 /**
1143 * Returns the thread group to which this thread belongs.
1144 * This method returns null if this thread has died
1145 * (been stopped).
1146 *
1147 * @return this thread's thread group.
1148 */
1149 public final ThreadGroup getThreadGroup() {
1150 return group;
1151 }
1152
1153 /**
1154 * Returns an estimate of the number of active threads in the current
1155 * thread's {@linkplain java.lang.ThreadGroup thread group} and its
1156 * subgroups. Recursively iterates over all subgroups in the current
1157 * thread's thread group.
1158 *
1159 * <p> The value returned is only an estimate because the number of
1160 * threads may change dynamically while this method traverses internal
1161 * data structures, and might be affected by the presence of certain
1162 * system threads. This method is intended primarily for debugging
1163 * and monitoring purposes.
1164 *
1165 * @return an estimate of the number of active threads in the current
1166 * thread's thread group and in any other thread group that
1167 * has the current thread's thread group as an ancestor
1168 */
1169 public static int activeCount() {
1170 return currentThread().getThreadGroup().activeCount();
1171 }
1172
1173 /**
1174 * Copies into the specified array every active thread in the current
1175 * thread's thread group and its subgroups. This method simply
1176 * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
1177 * method of the current thread's thread group.
1178 *
1179 * <p> An application might use the {@linkplain #activeCount activeCount}
1180 * method to get an estimate of how big the array should be, however
1181 * <i>if the array is too short to hold all the threads, the extra threads
1182 * are silently ignored.</i> If it is critical to obtain every active
1183 * thread in the current thread's thread group and its subgroups, the
1184 * invoker should verify that the returned int value is strictly less
1185 * than the length of {@code tarray}.
1186 *
1187 * <p> Due to the inherent race condition in this method, it is recommended
1188 * that the method only be used for debugging and monitoring purposes.
1189 *
1190 * @param tarray
1191 * an array into which to put the list of threads
1192 *
1193 * @return the number of threads put into the array
1194 *
1195 * @throws SecurityException
1196 * if {@link java.lang.ThreadGroup#checkAccess} determines that
1197 * the current thread cannot access its thread group
1198 */
1199 public static int enumerate(Thread tarray[]) {
1200 return currentThread().getThreadGroup().enumerate(tarray);
1201 }
1202
1203 /**
1204 * Counts the number of stack frames in this thread. The thread must
1205 * be suspended.
1206 *
1207 * @return the number of stack frames in this thread.
1208 * @exception IllegalThreadStateException if this thread is not
1209 * suspended.
1210 * @deprecated The definition of this call depends on {@link #suspend},
1211 * which is deprecated. Further, the results of this call
1212 * were never well-defined.
1213 */
1214 @Deprecated
1215 public native int countStackFrames();
1216
1217 /**
1218 * Waits at most {@code millis} milliseconds for this thread to
1219 * die. A timeout of {@code 0} means to wait forever.
1220 *
1221 * <p> This implementation uses a loop of {@code this.wait} calls
1222 * conditioned on {@code this.isAlive}. As a thread terminates the
1223 * {@code this.notifyAll} method is invoked. It is recommended that
1224 * applications not use {@code wait}, {@code notify}, or
1225 * {@code notifyAll} on {@code Thread} instances.
1226 *
1227 * @param millis
1228 * the time to wait in milliseconds
1229 *
1230 * @throws IllegalArgumentException
1231 * if the value of {@code millis} is negative
1232 *
1233 * @throws InterruptedException
1234 * if any thread has interrupted the current thread. The
1235 * <i>interrupted status</i> of the current thread is
1236 * cleared when this exception is thrown.
1237 */
1238 public final synchronized void join(long millis)
1239 throws InterruptedException {
1240 long base = System.currentTimeMillis();
1241 long now = 0;
1242
1243 if (millis < 0) {
1244 throw new IllegalArgumentException("timeout value is negative");
1245 }
1246
1247 if (millis == 0) {
1248 while (isAlive()) {
1249 wait(0);
1250 }
1251 } else {
1252 while (isAlive()) {
1253 long delay = millis - now;
1254 if (delay <= 0) {
1255 break;
1256 }
1257 wait(delay);
1258 now = System.currentTimeMillis() - base;
1259 }
1260 }
1261 }
1262
1263 /**
1264 * Waits at most {@code millis} milliseconds plus
1265 * {@code nanos} nanoseconds for this thread to die.
1266 *
1267 * <p> This implementation uses a loop of {@code this.wait} calls
1268 * conditioned on {@code this.isAlive}. As a thread terminates the
1269 * {@code this.notifyAll} method is invoked. It is recommended that
1270 * applications not use {@code wait}, {@code notify}, or
1271 * {@code notifyAll} on {@code Thread} instances.
1272 *
1273 * @param millis
1274 * the time to wait in milliseconds
1275 *
1276 * @param nanos
1277 * {@code 0-999999} additional nanoseconds to wait
1278 *
1279 * @throws IllegalArgumentException
1280 * if the value of {@code millis} is negative, or the value
1281 * of {@code nanos} is not in the range {@code 0-999999}
1282 *
1283 * @throws InterruptedException
1284 * if any thread has interrupted the current thread. The
1285 * <i>interrupted status</i> of the current thread is
1286 * cleared when this exception is thrown.
1287 */
1288 public final synchronized void join(long millis, int nanos)
1289 throws InterruptedException {
1290
1291 if (millis < 0) {
1292 throw new IllegalArgumentException("timeout value is negative");
1293 }
1294
1295 if (nanos < 0 || nanos > 999999) {
1296 throw new IllegalArgumentException(
1297 "nanosecond timeout value out of range");
1298 }
1299
1300 if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
1301 millis++;
1302 }
1303
1304 join(millis);
1305 }
1306
1307 /**
1308 * Waits for this thread to die.
1309 *
1310 * <p> An invocation of this method behaves in exactly the same
1311 * way as the invocation
1312 *
1313 * <blockquote>
1314 * {@linkplain #join(long) join}{@code (0)}
1315 * </blockquote>
1316 *
1317 * @throws InterruptedException
1318 * if any thread has interrupted the current thread. The
1319 * <i>interrupted status</i> of the current thread is
1320 * cleared when this exception is thrown.
1321 */
1322 public final void join() throws InterruptedException {
1323 join(0);
1324 }
1325
1326 /**
1327 * Prints a stack trace of the current thread to the standard error stream.
1328 * This method is used only for debugging.
1329 *
1330 * @see Throwable#printStackTrace()
1331 */
1332 public static void dumpStack() {
1333 new Exception("Stack trace").printStackTrace();
1334 }
1335
1336 /**
1337 * Marks this thread as either a {@linkplain #isDaemon daemon} thread
1338 * or a user thread. The Java Virtual Machine exits when the only
1339 * threads running are all daemon threads.
1340 *
1341 * <p> This method must be invoked before the thread is started.
1342 *
1343 * @param on
1344 * if {@code true}, marks this thread as a daemon thread
1345 *
1346 * @throws IllegalThreadStateException
1347 * if this thread is {@linkplain #isAlive alive}
1348 *
1349 * @throws SecurityException
1350 * if {@link #checkAccess} determines that the current
1351 * thread cannot modify this thread
1352 */
1353 public final void setDaemon(boolean on) {
1354 checkAccess();
1355 if (isAlive()) {
1356 throw new IllegalThreadStateException();
1357 }
1358 daemon = on;
1359 }
1360
1361 /**
1362 * Tests if this thread is a daemon thread.
1363 *
1364 * @return <code>true</code> if this thread is a daemon thread;
1365 * <code>false</code> otherwise.
1366 * @see #setDaemon(boolean)
1367 */
1368 public final boolean isDaemon() {
1369 return daemon;
1370 }
1371
1372 /**
1373 * Determines if the currently running thread has permission to
1374 * modify this thread.
1375 * <p>
1376 * If there is a security manager, its <code>checkAccess</code> method
1377 * is called with this thread as its argument. This may result in
1378 * throwing a <code>SecurityException</code>.
1379 *
1380 * @exception SecurityException if the current thread is not allowed to
1381 * access this thread.
1382 * @see SecurityManager#checkAccess(Thread)
1383 */
1384 public final void checkAccess() {
1385 SecurityManager security = System.getSecurityManager();
1386 if (security != null) {
1387 security.checkAccess(this);
1388 }
1389 }
1390
1391 /**
1392 * Returns a string representation of this thread, including the
1393 * thread's name, priority, and thread group.
1394 *
1395 * @return a string representation of this thread.
1396 */
1397 public String toString() {
1398 ThreadGroup group = getThreadGroup();
1399 if (group != null) {
1400 return "Thread[" + getName() + "," + getPriority() + "," +
1401 group.getName() + "]";
1402 } else {
1403 return "Thread[" + getName() + "," + getPriority() + "," +
1404 "" + "]";
1405 }
1406 }
1407
1408 /**
1409 * Returns the context ClassLoader for this Thread. The context
1410 * ClassLoader is provided by the creator of the thread for use
1411 * by code running in this thread when loading classes and resources.
1412 * If not {@linkplain #setContextClassLoader set}, the default is the
1413 * ClassLoader context of the parent Thread. The context ClassLoader of the
1414 * primordial thread is typically set to the class loader used to load the
1415 * application.
1416 *
1417 * <p>If a security manager is present, and the invoker's class loader is not
1418 * {@code null} and is not the same as or an ancestor of the context class
1419 * loader, then this method invokes the security manager's {@link
1420 * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1421 * method with a {@link RuntimePermission RuntimePermission}{@code
1422 * ("getClassLoader")} permission to verify that retrieval of the context
1423 * class loader is permitted.
1424 *
1425 * @return the context ClassLoader for this Thread, or {@code null}
1426 * indicating the system class loader (or, failing that, the
1427 * bootstrap class loader)
1428 *
1429 * @throws SecurityException
1430 * if the current thread cannot get the context ClassLoader
1431 *
1432 * @since 1.2
1433 */
1434 @CallerSensitive
1435 public ClassLoader getContextClassLoader() {
1436 if (contextClassLoader == null)
1437 return null;
1438 SecurityManager sm = System.getSecurityManager();
1439 if (sm != null) {
1440 ClassLoader.checkClassLoaderPermission(contextClassLoader,
1441 Reflection.getCallerClass());
1442 }
1443 return contextClassLoader;
1444 }
1445
1446 /**
1447 * Sets the context ClassLoader for this Thread. The context
1448 * ClassLoader can be set when a thread is created, and allows
1449 * the creator of the thread to provide the appropriate class loader,
1450 * through {@code getContextClassLoader}, to code running in the thread
1451 * when loading classes and resources.
1452 *
1453 * <p>If a security manager is present, its {@link
1454 * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1455 * method is invoked with a {@link RuntimePermission RuntimePermission}{@code
1456 * ("setContextClassLoader")} permission to see if setting the context
1457 * ClassLoader is permitted.
1458 *
1459 * @param cl
1460 * the context ClassLoader for this Thread, or null indicating the
1461 * system class loader (or, failing that, the bootstrap class loader)
1462 *
1463 * @throws SecurityException
1464 * if the current thread cannot set the context ClassLoader
1465 *
1466 * @since 1.2
1467 */
1468 public void setContextClassLoader(ClassLoader cl) {
1469 SecurityManager sm = System.getSecurityManager();
1470 if (sm != null) {
1471 sm.checkPermission(new RuntimePermission("setContextClassLoader"));
1472 }
1473 contextClassLoader = cl;
1474 }
1475
1476 /**
1477 * Returns <tt>true</tt> if and only if the current thread holds the
1478 * monitor lock on the specified object.
1479 *
1480 * <p>This method is designed to allow a program to assert that
1481 * the current thread already holds a specified lock:
1482 * <pre>
1483 * assert Thread.holdsLock(obj);
1484 * </pre>
1485 *
1486 * @param obj the object on which to test lock ownership
1487 * @throws NullPointerException if obj is <tt>null</tt>
1488 * @return <tt>true</tt> if the current thread holds the monitor lock on
1489 * the specified object.
1490 * @since 1.4
1491 */
1492 public static native boolean holdsLock(Object obj);
1493
1494 private static final StackTraceElement[] EMPTY_STACK_TRACE
1495 = new StackTraceElement[0];
1496
1497 /**
1498 * Returns an array of stack trace elements representing the stack dump
1499 * of this thread. This method will return a zero-length array if
1500 * this thread has not started, has started but has not yet been
1501 * scheduled to run by the system, or has terminated.
1502 * If the returned array is of non-zero length then the first element of
1503 * the array represents the top of the stack, which is the most recent
1504 * method invocation in the sequence. The last element of the array
1505 * represents the bottom of the stack, which is the least recent method
1506 * invocation in the sequence.
1507 *
1508 * <p>If there is a security manager, and this thread is not
1509 * the current thread, then the security manager's
1510 * <tt>checkPermission</tt> method is called with a
1511 * <tt>RuntimePermission("getStackTrace")</tt> permission
1512 * to see if it's ok to get the stack trace.
1513 *
1514 * <p>Some virtual machines may, under some circumstances, omit one
1515 * or more stack frames from the stack trace. In the extreme case,
1516 * a virtual machine that has no stack trace information concerning
1517 * this thread is permitted to return a zero-length array from this
1518 * method.
1519 *
1520 * @return an array of <tt>StackTraceElement</tt>,
1521 * each represents one stack frame.
1522 *
1523 * @throws SecurityException
1524 * if a security manager exists and its
1525 * <tt>checkPermission</tt> method doesn't allow
1526 * getting the stack trace of thread.
1527 * @see SecurityManager#checkPermission
1528 * @see RuntimePermission
1529 * @see Throwable#getStackTrace
1530 *
1531 * @since 1.5
1532 */
1533 public StackTraceElement[] getStackTrace() {
1534 if (this != Thread.currentThread()) {
1535 // check for getStackTrace permission
1536 SecurityManager security = System.getSecurityManager();
1537 if (security != null) {
1538 security.checkPermission(
1539 SecurityConstants.GET_STACK_TRACE_PERMISSION);
1540 }
1541 // optimization so we do not call into the vm for threads that
1542 // have not yet started or have terminated
1543 if (!isAlive()) {
1544 return EMPTY_STACK_TRACE;
1545 }
1546 StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
1547 StackTraceElement[] stackTrace = stackTraceArray[0];
1548 // a thread that was alive during the previous isAlive call may have
1549 // since terminated, therefore not having a stacktrace.
1550 if (stackTrace == null) {
1551 stackTrace = EMPTY_STACK_TRACE;
1552 }
1553 return stackTrace;
1554 } else {
1555 // Don't need JVM help for current thread
1556 return (new Exception()).getStackTrace();
1557 }
1558 }
1559
1560 /**
1561 * Returns a map of stack traces for all live threads.
1562 * The map keys are threads and each map value is an array of
1563 * <tt>StackTraceElement</tt> that represents the stack dump
1564 * of the corresponding <tt>Thread</tt>.
1565 * The returned stack traces are in the format specified for
1566 * the {@link #getStackTrace getStackTrace} method.
1567 *
1568 * <p>The threads may be executing while this method is called.
1569 * The stack trace of each thread only represents a snapshot and
1570 * each stack trace may be obtained at different time. A zero-length
1571 * array will be returned in the map value if the virtual machine has
1572 * no stack trace information about a thread.
1573 *
1574 * <p>If there is a security manager, then the security manager's
1575 * <tt>checkPermission</tt> method is called with a
1576 * <tt>RuntimePermission("getStackTrace")</tt> permission as well as
1577 * <tt>RuntimePermission("modifyThreadGroup")</tt> permission
1578 * to see if it is ok to get the stack trace of all threads.
1579 *
1580 * @return a <tt>Map</tt> from <tt>Thread</tt> to an array of
1581 * <tt>StackTraceElement</tt> that represents the stack trace of
1582 * the corresponding thread.
1583 *
1584 * @throws SecurityException
1585 * if a security manager exists and its
1586 * <tt>checkPermission</tt> method doesn't allow
1587 * getting the stack trace of thread.
1588 * @see #getStackTrace
1589 * @see SecurityManager#checkPermission
1590 * @see RuntimePermission
1591 * @see Throwable#getStackTrace
1592 *
1593 * @since 1.5
1594 */
1595 public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
1596 // check for getStackTrace permission
1597 SecurityManager security = System.getSecurityManager();
1598 if (security != null) {
1599 security.checkPermission(
1600 SecurityConstants.GET_STACK_TRACE_PERMISSION);
1601 security.checkPermission(
1602 SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
1603 }
1604
1605 // Get a snapshot of the list of all threads
1606 Thread[] threads = getThreads();
1607 StackTraceElement[][] traces = dumpThreads(threads);
1608 Map<Thread, StackTraceElement[]> m = new HashMap<>(threads.length);
1609 for (int i = 0; i < threads.length; i++) {
1610 StackTraceElement[] stackTrace = traces[i];
1611 if (stackTrace != null) {
1612 m.put(threads[i], stackTrace);
1613 }
1614 // else terminated so we don't put it in the map
1615 }
1616 return m;
1617 }
1618
1619
1620 private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
1621 new RuntimePermission("enableContextClassLoaderOverride");
1622
1623 /** cache of subclass security audit results */
1624 /* Replace with ConcurrentReferenceHashMap when/if it appears in a future
1625 * release */
1626 private static class Caches {
1627 /** cache of subclass security audit results */
1628 static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
1629 new ConcurrentHashMap<>();
1630
1631 /** queue for WeakReferences to audited subclasses */
1632 static final ReferenceQueue<Class<?>> subclassAuditsQueue =
1633 new ReferenceQueue<>();
1634 }
1635
1636 /**
1637 * Verifies that this (possibly subclass) instance can be constructed
1638 * without violating security constraints: the subclass must not override
1639 * security-sensitive non-final methods, or else the
1640 * "enableContextClassLoaderOverride" RuntimePermission is checked.
1641 */
1642 private static boolean isCCLOverridden(Class<?> cl) {
1643 if (cl == Thread.class)
1644 return false;
1645
1646 processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
1647 WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
1648 Boolean result = Caches.subclassAudits.get(key);
1649 if (result == null) {
1650 result = Boolean.valueOf(auditSubclass(cl));
1651 Caches.subclassAudits.putIfAbsent(key, result);
1652 }
1653
1654 return result.booleanValue();
1655 }
1656
1657 /**
1658 * Performs reflective checks on given subclass to verify that it doesn't
1659 * override security-sensitive non-final methods. Returns true if the
1660 * subclass overrides any of the methods, false otherwise.
1661 */
1662 private static boolean auditSubclass(final Class<?> subcl) {
1663 Boolean result = AccessController.doPrivileged(
1664 new PrivilegedAction<Boolean>() {
1665 public Boolean run() {
1666 for (Class<?> cl = subcl;
1667 cl != Thread.class;
1668 cl = cl.getSuperclass())
1669 {
1670 try {
1671 cl.getDeclaredMethod("getContextClassLoader", new Class<?>[0]);
1672 return Boolean.TRUE;
1673 } catch (NoSuchMethodException ex) {
1674 }
1675 try {
1676 Class<?>[] params = {ClassLoader.class};
1677 cl.getDeclaredMethod("setContextClassLoader", params);
1678 return Boolean.TRUE;
1679 } catch (NoSuchMethodException ex) {
1680 }
1681 }
1682 return Boolean.FALSE;
1683 }
1684 }
1685 );
1686 return result.booleanValue();
1687 }
1688
1689 private native static StackTraceElement[][] dumpThreads(Thread[] threads);
1690 private native static Thread[] getThreads();
1691
1692 /**
1693 * Returns the identifier of this Thread. The thread ID is a positive
1694 * <tt>long</tt> number generated when this thread was created.
1695 * The thread ID is unique and remains unchanged during its lifetime.
1696 * When a thread is terminated, this thread ID may be reused.
1697 *
1698 * @return this thread's ID.
1699 * @since 1.5
1700 */
1701 public long getId() {
1702 return tid;
1703 }
1704
1705 /**
1706 * A thread state. A thread can be in one of the following states:
1707 * <ul>
1708 * <li>{@link #NEW}<br>
1709 * A thread that has not yet started is in this state.
1710 * </li>
1711 * <li>{@link #RUNNABLE}<br>
1712 * A thread executing in the Java virtual machine is in this state.
1713 * </li>
1714 * <li>{@link #BLOCKED}<br>
1715 * A thread that is blocked waiting for a monitor lock
1716 * is in this state.
1717 * </li>
1718 * <li>{@link #WAITING}<br>
1719 * A thread that is waiting indefinitely for another thread to
1720 * perform a particular action is in this state.
1721 * </li>
1722 * <li>{@link #TIMED_WAITING}<br>
1723 * A thread that is waiting for another thread to perform an action
1724 * for up to a specified waiting time is in this state.
1725 * </li>
1726 * <li>{@link #TERMINATED}<br>
1727 * A thread that has exited is in this state.
1728 * </li>
1729 * </ul>
1730 *
1731 * <p>
1732 * A thread can be in only one state at a given point in time.
1733 * These states are virtual machine states which do not reflect
1734 * any operating system thread states.
1735 *
1736 * @since 1.5
1737 * @see #getState
1738 */
1739 public enum State {
1740 /**
1741 * Thread state for a thread which has not yet started.
1742 */
1743 NEW,
1744
1745 /**
1746 * Thread state for a runnable thread. A thread in the runnable
1747 * state is executing in the Java virtual machine but it may
1748 * be waiting for other resources from the operating system
1749 * such as processor.
1750 */
1751 RUNNABLE,
1752
1753 /**
1754 * Thread state for a thread blocked waiting for a monitor lock.
1755 * A thread in the blocked state is waiting for a monitor lock
1756 * to enter a synchronized block/method or
1757 * reenter a synchronized block/method after calling
1758 * {@link Object#wait() Object.wait}.
1759 */
1760 BLOCKED,
1761
1762 /**
1763 * Thread state for a waiting thread.
1764 * A thread is in the waiting state due to calling one of the
1765 * following methods:
1766 * <ul>
1767 * <li>{@link Object#wait() Object.wait} with no timeout</li>
1768 * <li>{@link #join() Thread.join} with no timeout</li>
1769 * <li>{@link LockSupport#park() LockSupport.park}</li>
1770 * </ul>
1771 *
1772 * <p>A thread in the waiting state is waiting for another thread to
1773 * perform a particular action.
1774 *
1775 * For example, a thread that has called <tt>Object.wait()</tt>
1776 * on an object is waiting for another thread to call
1777 * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
1778 * that object. A thread that has called <tt>Thread.join()</tt>
1779 * is waiting for a specified thread to terminate.
1780 */
1781 WAITING,
1782
1783 /**
1784 * Thread state for a waiting thread with a specified waiting time.
1785 * A thread is in the timed waiting state due to calling one of
1786 * the following methods with a specified positive waiting time:
1787 * <ul>
1788 * <li>{@link #sleep Thread.sleep}</li>
1789 * <li>{@link Object#wait(long) Object.wait} with timeout</li>
1790 * <li>{@link #join(long) Thread.join} with timeout</li>
1791 * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
1792 * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
1793 * </ul>
1794 */
1795 TIMED_WAITING,
1796
1797 /**
1798 * Thread state for a terminated thread.
1799 * The thread has completed execution.
1800 */
1801 TERMINATED;
1802 }
1803
1804 /**
1805 * Returns the state of this thread.
1806 * This method is designed for use in monitoring of the system state,
1807 * not for synchronization control.
1808 *
1809 * @return this thread's state.
1810 * @since 1.5
1811 */
1812 public State getState() {
1813 // get current thread state
1814 return sun.misc.VM.toThreadState(threadStatus);
1815 }
1816
1817 // Added in JSR-166
1818
1819 /**
1820 * Interface for handlers invoked when a <tt>Thread</tt> abruptly
1821 * terminates due to an uncaught exception.
1822 * <p>When a thread is about to terminate due to an uncaught exception
1823 * the Java Virtual Machine will query the thread for its
1824 * <tt>UncaughtExceptionHandler</tt> using
1825 * {@link #getUncaughtExceptionHandler} and will invoke the handler's
1826 * <tt>uncaughtException</tt> method, passing the thread and the
1827 * exception as arguments.
1828 * If a thread has not had its <tt>UncaughtExceptionHandler</tt>
1829 * explicitly set, then its <tt>ThreadGroup</tt> object acts as its
1830 * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object
1831 * has no
1832 * special requirements for dealing with the exception, it can forward
1833 * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
1834 * default uncaught exception handler}.
1835 *
1836 * @see #setDefaultUncaughtExceptionHandler
1837 * @see #setUncaughtExceptionHandler
1838 * @see ThreadGroup#uncaughtException
1839 * @since 1.5
1840 */
1841 @FunctionalInterface
1842 public interface UncaughtExceptionHandler {
1843 /**
1844 * Method invoked when the given thread terminates due to the
1845 * given uncaught exception.
1846 * <p>Any exception thrown by this method will be ignored by the
1847 * Java Virtual Machine.
1848 * @param t the thread
1849 * @param e the exception
1850 */
1851 void uncaughtException(Thread t, Throwable e);
1852 }
1853
1854 // null unless explicitly set
1855 private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
1856
1857 // null unless explicitly set
1858 private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
1859
1860 /**
1861 * Set the default handler invoked when a thread abruptly terminates
1862 * due to an uncaught exception, and no other handler has been defined
1863 * for that thread.
1864 *
1865 * <p>Uncaught exception handling is controlled first by the thread, then
1866 * by the thread's {@link ThreadGroup} object and finally by the default
1867 * uncaught exception handler. If the thread does not have an explicit
1868 * uncaught exception handler set, and the thread's thread group
1869 * (including parent thread groups) does not specialize its
1870 * <tt>uncaughtException</tt> method, then the default handler's
1871 * <tt>uncaughtException</tt> method will be invoked.
1872 * <p>By setting the default uncaught exception handler, an application
1873 * can change the way in which uncaught exceptions are handled (such as
1874 * logging to a specific device, or file) for those threads that would
1875 * already accept whatever "default" behavior the system
1876 * provided.
1877 *
1878 * <p>Note that the default uncaught exception handler should not usually
1879 * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause
1880 * infinite recursion.
1881 *
1882 * @param eh the object to use as the default uncaught exception handler.
1883 * If <tt>null</tt> then there is no default handler.
1884 *
1885 * @throws SecurityException if a security manager is present and it
1886 * denies <tt>{@link RuntimePermission}
1887 * ("setDefaultUncaughtExceptionHandler")</tt>
1888 *
1889 * @see #setUncaughtExceptionHandler
1890 * @see #getUncaughtExceptionHandler
1891 * @see ThreadGroup#uncaughtException
1892 * @since 1.5
1893 */
1894 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1895 SecurityManager sm = System.getSecurityManager();
1896 if (sm != null) {
1897 sm.checkPermission(
1898 new RuntimePermission("setDefaultUncaughtExceptionHandler")
1899 );
1900 }
1901
1902 defaultUncaughtExceptionHandler = eh;
1903 }
1904
1905 /**
1906 * Returns the default handler invoked when a thread abruptly terminates
1907 * due to an uncaught exception. If the returned value is <tt>null</tt>,
1908 * there is no default.
1909 * @since 1.5
1910 * @see #setDefaultUncaughtExceptionHandler
1911 * @return the default uncaught exception handler for all threads
1912 */
1913 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
1914 return defaultUncaughtExceptionHandler;
1915 }
1916
1917 /**
1918 * Returns the handler invoked when this thread abruptly terminates
1919 * due to an uncaught exception. If this thread has not had an
1920 * uncaught exception handler explicitly set then this thread's
1921 * <tt>ThreadGroup</tt> object is returned, unless this thread
1922 * has terminated, in which case <tt>null</tt> is returned.
1923 * @since 1.5
1924 * @return the uncaught exception handler for this thread
1925 */
1926 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
1927 return uncaughtExceptionHandler != null ?
1928 uncaughtExceptionHandler : group;
1929 }
1930
1931 /**
1932 * Set the handler invoked when this thread abruptly terminates
1933 * due to an uncaught exception.
1934 * <p>A thread can take full control of how it responds to uncaught
1935 * exceptions by having its uncaught exception handler explicitly set.
1936 * If no such handler is set then the thread's <tt>ThreadGroup</tt>
1937 * object acts as its handler.
1938 * @param eh the object to use as this thread's uncaught exception
1939 * handler. If <tt>null</tt> then this thread has no explicit handler.
1940 * @throws SecurityException if the current thread is not allowed to
1941 * modify this thread.
1942 * @see #setDefaultUncaughtExceptionHandler
1943 * @see ThreadGroup#uncaughtException
1944 * @since 1.5
1945 */
1946 public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1947 checkAccess();
1948 uncaughtExceptionHandler = eh;
1949 }
1950
1951 /**
1952 * Dispatch an uncaught exception to the handler. This method is
1953 * intended to be called only by the JVM.
1954 */
1955 private void dispatchUncaughtException(Throwable e) {
1956 getUncaughtExceptionHandler().uncaughtException(this, e);
1957 }
1958
1959 /**
1960 * Removes from the specified map any keys that have been enqueued
1961 * on the specified reference queue.
1962 */
1963 static void processQueue(ReferenceQueue<Class<?>> queue,
1964 ConcurrentMap<? extends
1965 WeakReference<Class<?>>, ?> map)
1966 {
1967 Reference<? extends Class<?>> ref;
1968 while((ref = queue.poll()) != null) {
1969 map.remove(ref);
1970 }
1971 }
1972
1973 /**
1974 * Weak key for Class objects.
1975 **/
1976 static class WeakClassKey extends WeakReference<Class<?>> {
1977 /**
1978 * saved value of the referent's identity hash code, to maintain
1979 * a consistent hash code after the referent has been cleared
1980 */
1981 private final int hash;
1982
1983 /**
1984 * Create a new WeakClassKey to the given object, registered
1985 * with a queue.
1986 */
1987 WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
1988 super(cl, refQueue);
1989 hash = System.identityHashCode(cl);
1990 }
1991
1992 /**
1993 * Returns the identity hash code of the original referent.
1994 */
1995 @Override
1996 public int hashCode() {
1997 return hash;
1998 }
1999
2000 /**
2001 * Returns true if the given object is this identical
2002 * WeakClassKey instance, or, if this object's referent has not
2003 * been cleared, if the given object is another WeakClassKey
2004 * instance with the identical non-null referent as this one.
2005 */
2006 @Override
2007 public boolean equals(Object obj) {
2008 if (obj == this)
2009 return true;
2010
2011 if (obj instanceof WeakClassKey) {
2012 Object referent = get();
2013 return (referent != null) &&
2014 (referent == ((WeakClassKey) obj).get());
2015 } else {
2016 return false;
2017 }
2018 }
2019 }
2020
2021
2022 // The following three initially uninitialized fields are exclusively
2023 // managed by class java.util.concurrent.ThreadLocalRandom. These
2024 // fields are used to build the high-performance PRNGs in the
2025 // concurrent code, and we can not risk accidental false sharing.
2026 // Hence, the fields are isolated with @Contended.
2027
2028 /** The current seed for a ThreadLocalRandom */
2029 @sun.misc.Contended("tlr")
2030 long threadLocalRandomSeed;
2031
2032 /** Probe hash value; nonzero if threadLocalRandomSeed initialized */
2033 @sun.misc.Contended("tlr")
2034 int threadLocalRandomProbe;
2035
2036 /** Secondary seed isolated from public ThreadLocalRandom sequence */
2037 @sun.misc.Contended("tlr")
2038 int threadLocalRandomSecondarySeed;
2039
2040 /* Some private helper methods */
2041 private native void setPriority0(int newPriority);
2042 private native void stop0(Object o);
2043 private native void suspend0();
2044 private native void resume0();
2045 private native void interrupt0();
2046 private native void setNativeName(String name);
2047 }
eclipse的outline视图如下:这里省略掉一些非公有的属性和方法
API属性方法清单:(新增)
一些属性和方法的探索:其中有相当一部分略过了,一部分是暂时还没接触到,一部分是没什么研究的必要。
构造方法摘要 | |
---|---|
Thread() 分配新的 Thread 对象。 |
|
Thread(Runnable target) 分配新的 Thread 对象。 |
|
Thread(Runnable target, String name) 分配新的 Thread 对象。 |
|
Thread(String name) 分配新的 Thread 对象。 |
|
Thread(ThreadGroup group, Runnable target) 分配新的 Thread 对象。 |
|
Thread(ThreadGroup group, Runnable target, String name) 分配新的 Thread 对象,以便将 target 作为其运行对象,将指定的 name 作为其名称,并作为 group 所引用的线程组的一员。 |
|
Thread(ThreadGroup group, Runnable target, String name, long stackSize) 分配新的 Thread 对象,以便将 target 作为其运行对象,将指定的 name 作为其名称,作为 group 所引用的线程组的一员,并具有指定的堆栈大小。 |
|
Thread(ThreadGroup group, String name) 分配新的 Thread 对象。 |
方法摘要 | |
static int |
activeCount() 返回当前线程的线程组中活动线程的数目。 |
void |
checkAccess() 判定当前运行的线程是否有权修改该线程。 |
int |
countStackFrames() 已过时。 该调用的定义依赖于 suspend() ,但它遭到了反对。此外,该调用的结果从来都不是意义明确的。 |
static Thread |
currentThread() 返回对当前正在执行的线程对象的引用。 |
void |
destroy() 已过时。 该方法最初用于破坏该线程,但不作任何清除。它所保持的任何监视器都会保持锁定状态。不过,该方法决不会被实现。即使要实现,它也极有可能以 suspend() 方式被死锁。如果目标线程被破坏时保持一个保护关键系统资源的锁,则任何线程在任何时候都无法再次访问该资源。如果另一个线程曾试图锁定该资源,则会出现死锁。这类死锁通常会证明它们自己是“冻结”的进程。有关更多信息,请参阅为何不赞成使用 Thread.stop、Thread.suspend 和 Thread.resume?。 |
static void |
dumpStack() 将当前线程的堆栈跟踪打印至标准错误流。 |
static int |
enumerate(Thread[] tarray) 将当前线程的线程组及其子组中的每一个活动线程复制到指定的数组中。 |
static Map<Thread,StackTraceElement[]> |
getAllStackTraces() 返回所有活动线程的堆栈跟踪的一个映射。 |
ClassLoader |
getContextClassLoader() 返回该线程的上下文 ClassLoader。 |
static Thread.UncaughtExceptionHandler |
getDefaultUncaughtExceptionHandler() 返回线程由于未捕获到异常而突然终止时调用的默认处理程序。 |
long |
getId() 返回该线程的标识符。 |
String |
getName() 返回该线程的名称。 |
int |
getPriority() 返回线程的优先级。 |
StackTraceElement[] |
getStackTrace() 返回一个表示该线程堆栈转储的堆栈跟踪元素数组。 |
Thread.State |
getState() 返回该线程的状态。 |
ThreadGroup |
getThreadGroup() 返回该线程所属的线程组。 |
Thread.UncaughtExceptionHandler |
getUncaughtExceptionHandler() 返回该线程由于未捕获到异常而突然终止时调用的处理程序。 |
static boolean |
holdsLock(Object obj) 当且仅当当前线程在指定的对象上保持监视器锁时,才返回 true。 |
void |
interrupt() 中断线程。 |
static boolean |
interrupted() 测试当前线程是否已经中断。 |
boolean |
isAlive() 测试线程是否处于活动状态。 |
boolean |
isDaemon() 测试该线程是否为守护线程。 |
boolean |
isInterrupted() 测试线程是否已经中断。 |
void |
join() 等待该线程终止。 |
void |
join(long millis) 等待该线程终止的时间最长为 millis 毫秒。 |
void |
join(long millis, int nanos) 等待该线程终止的时间最长为 millis 毫秒 + nanos 纳秒。 |
void |
resume() 已过时。 该方法只与 suspend() 一起使用,但 suspend() 已经遭到反对,因为它具有死锁倾向。有关更多信息,请参阅为何不赞成使用 Thread.stop、Thread.suspend 和 Thread.resume?。 |
void |
run() 如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;否则,该方法不执行任何操作并返回。 |
void |
setContextClassLoader(ClassLoader cl) 设置该线程的上下文 ClassLoader。 |
void |
setDaemon(boolean on) 将该线程标记为守护线程或用户线程。 |
static void |
setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) 设置当线程由于未捕获到异常而突然终止,并且没有为该线程定义其他处理程序时所调用的默认处理程序。 |
void |
setName(String name) 改变线程名称,使之与参数 name 相同。 |
void |
setPriority(int newPriority) 更改线程的优先级。 |
void |
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) 设置该线程由于未捕获到异常而突然终止时调用的处理程序。 |
static void |
sleep(long millis) 在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。 |
static void |
sleep(long millis, int nanos) 在指定的毫秒数加指定的纳秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。 |
void |
start() 使该线程开始执行;Java 虚拟机调用该线程的 run 方法。 |
void |
stop() 已过时。 该方法具有固有的不安全性。用 Thread.stop 来终止线程将释放它已经锁定的所有监视器(作为沿堆栈向上传播的未检查 ThreadDeath 异常的一个自然后果)。如果以前受这些监视器保护的任何对象都处于一种不一致的状态,则损坏的对象将对其他线程可见,这有可能导致任意的行为。stop 的许多使用都应由只修改某些变量以指示目标线程应该停止运行的代码来取代。目标线程应定期检查该变量,并且如果该变量指示它要停止运行,则从其运行方法依次返回。如果目标线程等待很长时间(例如基于一个条件变量),则应使用 interrupt 方法来中断该等待。有关更多信息,请参阅为何不赞成使用 Thread.stop、Thread.suspend 和 Thread.resume?。 |
void |
stop(Throwable obj) 已过时。 该方法具有固有的不安全性。有关详细信息,请参阅 stop() 。 该方法的附加危险是它可用于生成目标线程未准备处理的异常(包括若没有该方法该线程不太可能抛出的已检查的异常)。 有关更多信息,请参阅为何不赞成使用 Thread.stop、Thread.suspend 和 Thread.resume?。 |
void |
suspend() 已过时。 该方法已经遭到反对,因为它具有固有的死锁倾向。如果目标线程挂起时在保护关键系统资源的监视器上保持有锁,则在目标线程重新开始以前任何线程都不能访问该资源。如果重新开始目标线程的线程想在调用 resume 之前锁定该监视器,则会发生死锁。这类死锁通常会证明自己是“冻结”的进程。有关更多信息,请参阅为何不赞成使用 Thread.stop、Thread.suspend 和 Thread.resume?。 |
String |
toString() 返回该线程的字符串表示形式,包括线程名称、优先级和线程组。 |
static void |
yield() 暂停当前正在执行的线程对象,并执行其他线程。 |
三个属性:
MIN_PRIORITY: 一个线程可以拥有的最低优先级1
NORM_PRIORITY:分配给线程的默认优先级5
MAX_PRIORITY:一个线程能够拥有的最高优先级10
静态方法:(native方法都是需要VM底层实现的,我们在java源码中看不到具体的实现)
currentThread:返回对当前执行的线程对象的引用。(native方法)
yield:暂停当前正在执行的线程对象,并执行其他线程(native方法)
这个方法的目的是让当前运行线程回到就绪状态(可运行状态)用来让具有相同优先级其他线程可以运行(获得CPU资源),目的是为了同优先级的线程轮转,但实际是无法保证的,因为即使进入了就绪状态,相同的优先级他仍然可能被选择来执行。
sleep:线程休眠,参数指定休眠(暂停)的毫秒数。但是线程不损失任何资源的所有权。(native方法)
构造方法:
Thread的构造方法有很多重载,每个的参数有所不同,随便取几个看一下
。。。省略N个
这是参数最多的一个构造方法,看所有的构造方法我们发现,其实都是调用了同一个方法init(1,2,3,4)来进行初始化构造的,init有四个参数:
这个方法添加了第五个参数AccessControlContext=null再次调用了终极的初始化init,现成的构造方法中并没有用到这个参数,那就先略过(并没有搞清楚是干嘛的)
四个参数分别表示线程组,调用这个run方法的对象,线程名称,线程所需的堆栈大小。在init方法里,会获取到线程引用对象,然后检查参数,给线程属性赋值,这也是new一个线程的主要步骤。
接下来就是一些主要方法:
start():
启动线程,直接让线程进入就绪状态,同时与主线程分开执行,主线程会继续执行后面的方法,二线程则会等待CPU资源,获取CPU资源之后开始运行RUN方法内的内容,RUN方法中包含了线程的需要执行的所有内容,执行完毕,线程结束。
下面是start的源码,可以看到start方法只是设置了状态,并且调用了start0这个native方法,这个方法这里并没有具体实现也没有调用RUN方法去执行,原因是start0是个native方法,是由VM虚拟机本身的机制实现的(JVM的实现大部分是跟OS相关的,所以OS不同的话可能实现的机制有差异)。
注释中也有写到:the Java Virtual Machine calls the <code>run</code> method of this thread .java虚拟机调用run方法执行线程。如果想看具体的实现大家可以参考:http://blog.csdn.net/jeffhtlee/article/details/12751825,这里面写的比较清楚。
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> 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</code> method) and the other thread (which executes its
* <code>run</code> 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.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
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 */
}
}
}
private native void start0();//
start0方法运行起来了,调用Run执行方法体(具体的业务)。
Join(millis):
等待millisseconds后这个线程就不再等待(最大等待时间),当millisseconds=0,就是无限等待,直到这个线程执行完毕。(等待调用的是Object的wait方法)
1 /**
2 * Waits at most {@code millis} milliseconds for this thread to
3 * die. A timeout of {@code 0} means to wait forever.
4 *
5 * <p> This implementation uses a loop of {@code this.wait} calls
6 * conditioned on {@code this.isAlive}. As a thread terminates the
7 * {@code this.notifyAll} method is invoked. It is recommended that
8 * applications not use {@code wait}, {@code notify}, or
9 * {@code notifyAll} on {@code Thread} instances.
10 *
11 * @param millis
12 * the time to wait in milliseconds
13 *
14 * @throws IllegalArgumentException
15 * if the value of {@code millis} is negative
16 *
17 * @throws InterruptedException
18 * if any thread has interrupted the current thread. The
19 * <i>interrupted status</i> of the current thread is
20 * cleared when this exception is thrown.
21 */
22 public final synchronized void join(long millis)
23 throws InterruptedException {
24 long base = System.currentTimeMillis();
25 long now = 0;
26
27 if (millis < 0) {
28 throw new IllegalArgumentException("timeout value is negative");
29 }
30
31 if (millis == 0) {
32 while (isAlive()) {
33 wait(0);//此时调用的是wait(0)方法继承的是object的方法
34 }
35 } else {
36 while (isAlive()) {//这里调用了isAlive方法也是个native方法
37 long delay = millis - now;
38 if (delay <= 0) {
39 break;
40 }
41 wait(delay);
42 now = System.currentTimeMillis() - base;
43 }
44 }
45 }
exit():
private,私有的方法,这个方法是在Run方法执行结束后用于结束线程的。通过单步调试一个线程发现执行完run方法之后会进入exit方法。
注释中写到: This method is called by the system to give a Thread a chance to clean up before it actually exits.由系统调用这个方法释放资源在线程退出之前(不知道翻译的对不对)。
1 /**
2 * This method is called by the system to give a Thread
3 * a chance to clean up before it actually exits.
4 */
5 private void exit() {
6 if (group != null) {
7 group.threadTerminated(this);
8 group = null;
9 }
10 /* Aggressively null out all reference fields: see bug 4006245 */
11 target = null;
12 /* Speed the release of some of these resources */
13 threadLocals = null;
14 inheritableThreadLocals = null;
15 inheritedAccessControlContext = null;
16 blocker = null;
17 uncaughtExceptionHandler = null;
18 }
state:
枚举类型,线程的状态( NEW, RUNNABLE,BLOCKED,WAITING, TIMED_WAITING,TERMINATED),通过getState()方法可以获取到当前线程的状态。
无论是实现Runable接口还是继承Thread类,最终启动线程的时候我们发现都是调用的start()方法,说明他们最终的都是要通过Thread这个实现类来进行各种操作。通过Runable实现的线程最终还是调用Thread类中的方法和属性。至于两种方式创建的线程存在什么区别,以及是否存在性能上的差异,暂时还没有进一步研究.
❤如果这篇文章对你有一点点的帮助请给一份推荐! 谢谢!你们的鼓励是我继续前进的动力。更多内容欢迎访问我的个人博客
❤本博客只适用于研究学习为目的,大多为学习笔记,如有错误欢迎指正,如有误导概不负责(本人尽力保证90%的验证和10%的猜想)。