2 * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
32 * A <i>thread</i> is a thread of execution in a program. The Java
33 * Virtual Machine allows an application to have multiple threads of
34 * execution running concurrently.
36 * Every thread has a priority. Threads with higher priority are
37 * executed in preference to threads with lower priority. Each thread
38 * may or may not also be marked as a daemon. When code running in
39 * some thread creates a new <code>Thread</code> object, the new
40 * thread has its priority initially set equal to the priority of the
41 * creating thread, and is a daemon thread if and only if the
42 * creating thread is a daemon.
44 * When a Java Virtual Machine starts up, there is usually a single
45 * non-daemon thread (which typically calls the method named
46 * <code>main</code> of some designated class). The Java Virtual
47 * Machine continues to execute threads until either of the following
50 * <li>The <code>exit</code> method of class <code>Runtime</code> has been
51 * called and the security manager has permitted the exit operation
53 * <li>All threads that are not daemon threads have died, either by
54 * returning from the call to the <code>run</code> method or by
55 * throwing an exception that propagates beyond the <code>run</code>
59 * There are two ways to create a new thread of execution. One is to
60 * declare a class to be a subclass of <code>Thread</code>. This
61 * subclass should override the <code>run</code> method of class
62 * <code>Thread</code>. An instance of the subclass can then be
63 * allocated and started. For example, a thread that computes primes
64 * larger than a stated value could be written as follows:
65 * <p><hr><blockquote><pre>
66 * class PrimeThread extends Thread {
68 * PrimeThread(long minPrime) {
69 * this.minPrime = minPrime;
73 * // compute primes larger than minPrime
74 * . . .
77 * </pre></blockquote><hr>
79 * The following code would then create a thread and start it running:
80 * <p><blockquote><pre>
81 * PrimeThread p = new PrimeThread(143);
85 * The other way to create a thread is to declare a class that
86 * implements the <code>Runnable</code> interface. That class then
87 * implements the <code>run</code> method. An instance of the class can
88 * then be allocated, passed as an argument when creating
89 * <code>Thread</code>, and started. The same example in this other
90 * style looks like the following:
91 * <p><hr><blockquote><pre>
92 * class PrimeRun implements Runnable {
94 * PrimeRun(long minPrime) {
95 * this.minPrime = minPrime;
99 * // compute primes larger than minPrime
100 * . . .
103 * </pre></blockquote><hr>
105 * The following code would then create a thread and start it running:
106 * <p><blockquote><pre>
107 * PrimeRun p = new PrimeRun(143);
108 * new Thread(p).start();
109 * </pre></blockquote>
111 * Every thread has a name for identification purposes. More than
112 * one thread may have the same name. If a name is not specified when
113 * a thread is created, a new name is generated for it.
115 * Unless otherwise noted, passing a {@code null} argument to a constructor
116 * or method in this class will cause a {@link NullPointerException} to be
121 * @see Runtime#exit(int)
127 class Thread implements Runnable {
130 * The minimum priority that a thread can have.
132 public final static int MIN_PRIORITY = 1;
135 * The default priority that is assigned to a thread.
137 public final static int NORM_PRIORITY = 5;
140 * The maximum priority that a thread can have.
142 public final static int MAX_PRIORITY = 10;
144 private static final Thread ONE = new Thread("main");
146 * Returns a reference to the currently executing thread object.
148 * @return the currently executing thread.
150 public static Thread currentThread() {
155 * A hint to the scheduler that the current thread is willing to yield
156 * its current use of a processor. The scheduler is free to ignore this
159 * <p> Yield is a heuristic attempt to improve relative progression
160 * between threads that would otherwise over-utilise a CPU. Its use
161 * should be combined with detailed profiling and benchmarking to
162 * ensure that it actually has the desired effect.
164 * <p> It is rarely appropriate to use this method. It may be useful
165 * for debugging or testing purposes, where it may help to reproduce
166 * bugs due to race conditions. It may also be useful when designing
167 * concurrency control constructs such as the ones in the
168 * {@link java.util.concurrent.locks} package.
170 public static void yield() {
174 * Causes the currently executing thread to sleep (temporarily cease
175 * execution) for the specified number of milliseconds, subject to
176 * the precision and accuracy of system timers and schedulers. The thread
177 * does not lose ownership of any monitors.
180 * the length of time to sleep in milliseconds
182 * @throws IllegalArgumentException
183 * if the value of {@code millis} is negative
185 * @throws InterruptedException
186 * if any thread has interrupted the current thread. The
187 * <i>interrupted status</i> of the current thread is
188 * cleared when this exception is thrown.
190 public static native void sleep(long millis) throws InterruptedException;
193 * Causes the currently executing thread to sleep (temporarily cease
194 * execution) for the specified number of milliseconds plus the specified
195 * number of nanoseconds, subject to the precision and accuracy of system
196 * timers and schedulers. The thread does not lose ownership of any
200 * the length of time to sleep in milliseconds
203 * {@code 0-999999} additional nanoseconds to sleep
205 * @throws IllegalArgumentException
206 * if the value of {@code millis} is negative, or the value of
207 * {@code nanos} is not in the range {@code 0-999999}
209 * @throws InterruptedException
210 * if any thread has interrupted the current thread. The
211 * <i>interrupted status</i> of the current thread is
212 * cleared when this exception is thrown.
214 public static void sleep(long millis, int nanos)
215 throws InterruptedException {
217 throw new IllegalArgumentException("timeout value is negative");
220 if (nanos < 0 || nanos > 999999) {
221 throw new IllegalArgumentException(
222 "nanosecond timeout value out of range");
225 if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
231 private Runnable target;
235 * Throws CloneNotSupportedException as a Thread can not be meaningfully
236 * cloned. Construct a new Thread instead.
238 * @throws CloneNotSupportedException
242 protected Object clone() throws CloneNotSupportedException {
243 throw new CloneNotSupportedException();
247 * Allocates a new {@code Thread} object. This constructor has the same
248 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
249 * {@code (null, null, gname)}, where {@code gname} is a newly generated
250 * name. Automatically generated names are of the form
251 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
254 init(null, null, "Thread-" + nextThreadNum(), 0);
257 private static int nextThreadNum() {
262 * Allocates a new {@code Thread} object. This constructor has the same
263 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
264 * {@code (null, target, gname)}, where {@code gname} is a newly generated
265 * name. Automatically generated names are of the form
266 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
269 * the object whose {@code run} method is invoked when this thread
270 * is started. If {@code null}, this classes {@code run} method does
273 public Thread(Runnable target) {
274 init(null, target, "Thread-" + nextThreadNum(), 0);
278 * Allocates a new {@code Thread} object. This constructor has the same
279 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
280 * {@code (group, target, gname)} ,where {@code gname} is a newly generated
281 * name. Automatically generated names are of the form
282 * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
285 * the thread group. If {@code null} and there is a security
286 * manager, the group is determined by {@linkplain
287 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
288 * If there is not a security manager or {@code
289 * SecurityManager.getThreadGroup()} returns {@code null}, the group
290 * is set to the current thread's thread group.
293 * the object whose {@code run} method is invoked when this thread
294 * is started. If {@code null}, this thread's run method is invoked.
296 * @throws SecurityException
297 * if the current thread cannot create a thread in the specified
300 // public Thread(ThreadGroup group, Runnable target) {
301 // init(group, target, "Thread-" + nextThreadNum(), 0);
305 * Allocates a new {@code Thread} object. This constructor has the same
306 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
307 * {@code (null, null, name)}.
310 * the name of the new thread
312 public Thread(String name) {
313 init(null, null, name, 0);
316 private void init(Object o1, Runnable trgt, String nm, int i4) {
322 * Allocates a new {@code Thread} object. This constructor has the same
323 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
324 * {@code (group, null, name)}.
327 * the thread group. If {@code null} and there is a security
328 * manager, the group is determined by {@linkplain
329 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
330 * If there is not a security manager or {@code
331 * SecurityManager.getThreadGroup()} returns {@code null}, the group
332 * is set to the current thread's thread group.
335 * the name of the new thread
337 * @throws SecurityException
338 * if the current thread cannot create a thread in the specified
341 // public Thread(ThreadGroup group, String name) {
342 // init(group, null, name, 0);
346 * Allocates a new {@code Thread} object. This constructor has the same
347 * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
348 * {@code (null, target, name)}.
351 * the object whose {@code run} method is invoked when this thread
352 * is started. If {@code null}, this thread's run method is invoked.
355 * the name of the new thread
357 public Thread(Runnable target, String name) {
358 init(null, target, name, 0);
362 * Allocates a new {@code Thread} object so that it has {@code target}
363 * as its run object, has the specified {@code name} as its name,
364 * and belongs to the thread group referred to by {@code group}.
366 * <p>If there is a security manager, its
367 * {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
368 * method is invoked with the ThreadGroup as its argument.
370 * <p>In addition, its {@code checkPermission} method is invoked with
371 * the {@code RuntimePermission("enableContextClassLoaderOverride")}
372 * permission when invoked directly or indirectly by the constructor
373 * of a subclass which overrides the {@code getContextClassLoader}
374 * or {@code setContextClassLoader} methods.
376 * <p>The priority of the newly created thread is set equal to the
377 * priority of the thread creating it, that is, the currently running
378 * thread. The method {@linkplain #setPriority setPriority} may be
379 * used to change the priority to a new value.
381 * <p>The newly created thread is initially marked as being a daemon
382 * thread if and only if the thread creating it is currently marked
383 * as a daemon thread. The method {@linkplain #setDaemon setDaemon}
384 * may be used to change whether or not a thread is a daemon.
387 * the thread group. If {@code null} and there is a security
388 * manager, the group is determined by {@linkplain
389 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
390 * If there is not a security manager or {@code
391 * SecurityManager.getThreadGroup()} returns {@code null}, the group
392 * is set to the current thread's thread group.
395 * the object whose {@code run} method is invoked when this thread
396 * is started. If {@code null}, this thread's run method is invoked.
399 * the name of the new thread
401 * @throws SecurityException
402 * if the current thread cannot create a thread in the specified
403 * thread group or cannot override the context class loader methods.
405 // public Thread(ThreadGroup group, Runnable target, String name) {
406 // init(group, target, name, 0);
410 * Allocates a new {@code Thread} object so that it has {@code target}
411 * as its run object, has the specified {@code name} as its name,
412 * and belongs to the thread group referred to by {@code group}, and has
413 * the specified <i>stack size</i>.
415 * <p>This constructor is identical to {@link
416 * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
417 * that it allows the thread stack size to be specified. The stack size
418 * is the approximate number of bytes of address space that the virtual
419 * machine is to allocate for this thread's stack. <b>The effect of the
420 * {@code stackSize} parameter, if any, is highly platform dependent.</b>
422 * <p>On some platforms, specifying a higher value for the
423 * {@code stackSize} parameter may allow a thread to achieve greater
424 * recursion depth before throwing a {@link StackOverflowError}.
425 * Similarly, specifying a lower value may allow a greater number of
426 * threads to exist concurrently without throwing an {@link
427 * OutOfMemoryError} (or other internal error). The details of
428 * the relationship between the value of the <tt>stackSize</tt> parameter
429 * and the maximum recursion depth and concurrency level are
430 * platform-dependent. <b>On some platforms, the value of the
431 * {@code stackSize} parameter may have no effect whatsoever.</b>
433 * <p>The virtual machine is free to treat the {@code stackSize}
434 * parameter as a suggestion. If the specified value is unreasonably low
435 * for the platform, the virtual machine may instead use some
436 * platform-specific minimum value; if the specified value is unreasonably
437 * high, the virtual machine may instead use some platform-specific
438 * maximum. Likewise, the virtual machine is free to round the specified
439 * value up or down as it sees fit (or to ignore it completely).
441 * <p>Specifying a value of zero for the {@code stackSize} parameter will
442 * cause this constructor to behave exactly like the
443 * {@code Thread(ThreadGroup, Runnable, String)} constructor.
445 * <p><i>Due to the platform-dependent nature of the behavior of this
446 * constructor, extreme care should be exercised in its use.
447 * The thread stack size necessary to perform a given computation will
448 * likely vary from one JRE implementation to another. In light of this
449 * variation, careful tuning of the stack size parameter may be required,
450 * and the tuning may need to be repeated for each JRE implementation on
451 * which an application is to run.</i>
453 * <p>Implementation note: Java platform implementers are encouraged to
454 * document their implementation's behavior with respect to the
455 * {@code stackSize} parameter.
459 * the thread group. If {@code null} and there is a security
460 * manager, the group is determined by {@linkplain
461 * SecurityManager#getThreadGroup SecurityManager.getThreadGroup()}.
462 * If there is not a security manager or {@code
463 * SecurityManager.getThreadGroup()} returns {@code null}, the group
464 * is set to the current thread's thread group.
467 * the object whose {@code run} method is invoked when this thread
468 * is started. If {@code null}, this thread's run method is invoked.
471 * the name of the new thread
474 * the desired stack size for the new thread, or zero to indicate
475 * that this parameter is to be ignored.
477 * @throws SecurityException
478 * if the current thread cannot create a thread in the specified
483 // public Thread(ThreadGroup group, Runnable target, String name,
485 // init(group, target, name, stackSize);
489 * Causes this thread to begin execution; the Java Virtual Machine
490 * calls the <code>run</code> method of this thread.
492 * The result is that two threads are running concurrently: the
493 * current thread (which returns from the call to the
494 * <code>start</code> method) and the other thread (which executes its
495 * <code>run</code> method).
497 * It is never legal to start a thread more than once.
498 * In particular, a thread may not be restarted once it has completed
501 * @exception IllegalThreadStateException if the thread was already
506 public void start() {
507 throw new SecurityException();
511 * If this thread was constructed using a separate
512 * <code>Runnable</code> run object, then that
513 * <code>Runnable</code> object's <code>run</code> method is called;
514 * otherwise, this method does nothing and returns.
516 * Subclasses of <code>Thread</code> should override this method.
520 * @see #Thread(ThreadGroup, Runnable, String)
524 if (target != null) {
530 * Forces the thread to stop executing.
532 * If there is a security manager installed, its <code>checkAccess</code>
533 * method is called with <code>this</code>
534 * as its argument. This may result in a
535 * <code>SecurityException</code> being raised (in the current thread).
537 * If this thread is different from the current thread (that is, the current
538 * thread is trying to stop a thread other than itself), the
539 * security manager's <code>checkPermission</code> method (with a
540 * <code>RuntimePermission("stopThread")</code> argument) is called in
542 * Again, this may result in throwing a
543 * <code>SecurityException</code> (in the current thread).
545 * The thread represented by this thread is forced to stop whatever
546 * it is doing abnormally and to throw a newly created
547 * <code>ThreadDeath</code> object as an exception.
549 * It is permitted to stop a thread that has not yet been started.
550 * If the thread is eventually started, it immediately terminates.
552 * An application should not normally try to catch
553 * <code>ThreadDeath</code> unless it must do some extraordinary
554 * cleanup operation (note that the throwing of
555 * <code>ThreadDeath</code> causes <code>finally</code> clauses of
556 * <code>try</code> statements to be executed before the thread
557 * officially dies). If a <code>catch</code> clause catches a
558 * <code>ThreadDeath</code> object, it is important to rethrow the
559 * object so that the thread actually dies.
561 * The top-level error handler that reacts to otherwise uncaught
562 * exceptions does not print out a message or otherwise notify the
563 * application if the uncaught exception is an instance of
564 * <code>ThreadDeath</code>.
566 * @exception SecurityException if the current thread cannot
567 * modify this thread.
569 * @see #checkAccess()
573 * @see ThreadGroup#uncaughtException(Thread,Throwable)
574 * @see SecurityManager#checkAccess(Thread)
575 * @see SecurityManager#checkPermission
576 * @deprecated This method is inherently unsafe. Stopping a thread with
577 * Thread.stop causes it to unlock all of the monitors that it
578 * has locked (as a natural consequence of the unchecked
579 * <code>ThreadDeath</code> exception propagating up the stack). If
580 * any of the objects previously protected by these monitors were in
581 * an inconsistent state, the damaged objects become visible to
582 * other threads, potentially resulting in arbitrary behavior. Many
583 * uses of <code>stop</code> should be replaced by code that simply
584 * modifies some variable to indicate that the target thread should
585 * stop running. The target thread should check this variable
586 * regularly, and return from its run method in an orderly fashion
587 * if the variable indicates that it is to stop running. If the
588 * target thread waits for long periods (on a condition variable,
589 * for example), the <code>interrupt</code> method should be used to
590 * interrupt the wait.
591 * For more information, see
592 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
593 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
596 public final void stop() {
601 * Forces the thread to stop executing.
603 * If there is a security manager installed, the <code>checkAccess</code>
604 * method of this thread is called, which may result in a
605 * <code>SecurityException</code> being raised (in the current thread).
607 * If this thread is different from the current thread (that is, the current
608 * thread is trying to stop a thread other than itself) or
609 * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
610 * security manager's <code>checkPermission</code> method (with the
611 * <code>RuntimePermission("stopThread")</code> argument) is called in
613 * Again, this may result in throwing a
614 * <code>SecurityException</code> (in the current thread).
616 * If the argument <code>obj</code> is null, a
617 * <code>NullPointerException</code> is thrown (in the current thread).
619 * The thread represented by this thread is forced to stop
620 * whatever it is doing abnormally and to throw the
621 * <code>Throwable</code> object <code>obj</code> as an exception. This
622 * is an unusual action to take; normally, the <code>stop</code> method
623 * that takes no arguments should be used.
625 * It is permitted to stop a thread that has not yet been started.
626 * If the thread is eventually started, it immediately terminates.
628 * @param obj the Throwable object to be thrown.
629 * @exception SecurityException if the current thread cannot modify
631 * @throws NullPointerException if obj is <tt>null</tt>.
633 * @see #checkAccess()
637 * @see SecurityManager#checkAccess(Thread)
638 * @see SecurityManager#checkPermission
639 * @deprecated This method is inherently unsafe. See {@link #stop()}
640 * for details. An additional danger of this
641 * method is that it may be used to generate exceptions that the
642 * target thread is unprepared to handle (including checked
643 * exceptions that the thread could not possibly throw, were it
644 * not for this method).
645 * For more information, see
646 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
647 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
650 public final synchronized void stop(Throwable obj) {
651 throw new SecurityException();
655 * Interrupts this thread.
657 * <p> Unless the current thread is interrupting itself, which is
658 * always permitted, the {@link #checkAccess() checkAccess} method
659 * of this thread is invoked, which may cause a {@link
660 * SecurityException} to be thrown.
662 * <p> If this thread is blocked in an invocation of the {@link
663 * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
664 * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
665 * class, or of the {@link #join()}, {@link #join(long)}, {@link
666 * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
667 * methods of this class, then its interrupt status will be cleared and it
668 * will receive an {@link InterruptedException}.
670 * <p> If this thread is blocked in an I/O operation upon an {@link
671 * java.nio.channels.InterruptibleChannel </code>interruptible
672 * channel<code>} then the channel will be closed, the thread's interrupt
673 * status will be set, and the thread will receive a {@link
674 * java.nio.channels.ClosedByInterruptException}.
676 * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
677 * then the thread's interrupt status will be set and it will return
678 * immediately from the selection operation, possibly with a non-zero
679 * value, just as if the selector's {@link
680 * java.nio.channels.Selector#wakeup wakeup} method were invoked.
682 * <p> If none of the previous conditions hold then this thread's interrupt
683 * status will be set. </p>
685 * <p> Interrupting a thread that is not alive need not have any effect.
687 * @throws SecurityException
688 * if the current thread cannot modify this thread
693 public void interrupt() {
694 throw new SecurityException();
698 * Tests whether the current thread has been interrupted. The
699 * <i>interrupted status</i> of the thread is cleared by this method. In
700 * other words, if this method were to be called twice in succession, the
701 * second call would return false (unless the current thread were
702 * interrupted again, after the first call had cleared its interrupted
703 * status and before the second call had examined it).
705 * <p>A thread interruption ignored because a thread was not alive
706 * at the time of the interrupt will be reflected by this method
709 * @return <code>true</code> if the current thread has been interrupted;
710 * <code>false</code> otherwise.
711 * @see #isInterrupted()
714 public static boolean interrupted() {
715 return currentThread().isInterrupted();
719 * Tests whether this thread has been interrupted. The <i>interrupted
720 * status</i> of the thread is unaffected by this method.
722 * <p>A thread interruption ignored because a thread was not alive
723 * at the time of the interrupt will be reflected by this method
726 * @return <code>true</code> if this thread has been interrupted;
727 * <code>false</code> otherwise.
728 * @see #interrupted()
731 public boolean isInterrupted() {
736 * Throws {@link NoSuchMethodError}.
738 * @deprecated This method was originally designed to destroy this
739 * thread without any cleanup. Any monitors it held would have
740 * remained locked. However, the method was never implemented.
741 * If if were to be implemented, it would be deadlock-prone in
742 * much the manner of {@link #suspend}. If the target thread held
743 * a lock protecting a critical system resource when it was
744 * destroyed, no thread could ever access this resource again.
745 * If another thread ever attempted to lock this resource, deadlock
746 * would result. Such deadlocks typically manifest themselves as
747 * "frozen" processes. For more information, see
748 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">
749 * Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
750 * @throws NoSuchMethodError always
753 public void destroy() {
754 throw new SecurityException();
758 * Tests if this thread is alive. A thread is alive if it has
759 * been started and has not yet died.
761 * @return <code>true</code> if this thread is alive;
762 * <code>false</code> otherwise.
764 public final boolean isAlive() {
769 * Suspends this thread.
771 * First, the <code>checkAccess</code> method of this thread is called
772 * with no arguments. This may result in throwing a
773 * <code>SecurityException </code>(in the current thread).
775 * If the thread is alive, it is suspended and makes no further
776 * progress unless and until it is resumed.
778 * @exception SecurityException if the current thread cannot modify
781 * @deprecated This method has been deprecated, as it is
782 * inherently deadlock-prone. If the target thread holds a lock on the
783 * monitor protecting a critical system resource when it is suspended, no
784 * thread can access this resource until the target thread is resumed. If
785 * the thread that would resume the target thread attempts to lock this
786 * monitor prior to calling <code>resume</code>, deadlock results. Such
787 * deadlocks typically manifest themselves as "frozen" processes.
788 * For more information, see
789 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
790 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
793 public final void suspend() {
798 * Resumes a suspended thread.
800 * First, the <code>checkAccess</code> method of this thread is called
801 * with no arguments. This may result in throwing a
802 * <code>SecurityException</code> (in the current thread).
804 * If the thread is alive but suspended, it is resumed and is
805 * permitted to make progress in its execution.
807 * @exception SecurityException if the current thread cannot modify this
811 * @deprecated This method exists solely for use with {@link #suspend},
812 * which has been deprecated because it is deadlock-prone.
813 * For more information, see
814 * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
815 * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
818 public final void resume() {
823 * Changes the priority of this thread.
825 * First the <code>checkAccess</code> method of this thread is called
826 * with no arguments. This may result in throwing a
827 * <code>SecurityException</code>.
829 * Otherwise, the priority of this thread is set to the smaller of
830 * the specified <code>newPriority</code> and the maximum permitted
831 * priority of the thread's thread group.
833 * @param newPriority priority to set this thread to
834 * @exception IllegalArgumentException If the priority is not in the
835 * range <code>MIN_PRIORITY</code> to
836 * <code>MAX_PRIORITY</code>.
837 * @exception SecurityException if the current thread cannot modify
840 * @see #checkAccess()
841 * @see #getThreadGroup()
844 * @see ThreadGroup#getMaxPriority()
846 public final void setPriority(int newPriority) {
847 throw new SecurityException();
851 * Returns this thread's priority.
853 * @return this thread's priority.
856 public final int getPriority() {
857 return Thread.NORM_PRIORITY;
861 * Changes the name of this thread to be equal to the argument
864 * First the <code>checkAccess</code> method of this thread is called
865 * with no arguments. This may result in throwing a
866 * <code>SecurityException</code>.
868 * @param name the new name for this thread.
869 * @exception SecurityException if the current thread cannot modify this
872 * @see #checkAccess()
874 public final void setName(String name) {
875 throw new SecurityException();
879 * Returns this thread's name.
881 * @return this thread's name.
882 * @see #setName(String)
884 public final String getName() {
885 return String.valueOf(name);
889 * Returns the thread group to which this thread belongs.
890 * This method returns null if this thread has died
893 * @return this thread's thread group.
895 // public final ThreadGroup getThreadGroup() {
900 * Returns an estimate of the number of active threads in the current
901 * thread's {@linkplain java.lang.ThreadGroup thread group} and its
902 * subgroups. Recursively iterates over all subgroups in the current
903 * thread's thread group.
905 * <p> The value returned is only an estimate because the number of
906 * threads may change dynamically while this method traverses internal
907 * data structures, and might be affected by the presence of certain
908 * system threads. This method is intended primarily for debugging
909 * and monitoring purposes.
911 * @return an estimate of the number of active threads in the current
912 * thread's thread group and in any other thread group that
913 * has the current thread's thread group as an ancestor
915 public static int activeCount() {
920 * Copies into the specified array every active thread in the current
921 * thread's thread group and its subgroups. This method simply
922 * invokes the {@link java.lang.ThreadGroup#enumerate(Thread[])}
923 * method of the current thread's thread group.
925 * <p> An application might use the {@linkplain #activeCount activeCount}
926 * method to get an estimate of how big the array should be, however
927 * <i>if the array is too short to hold all the threads, the extra threads
928 * are silently ignored.</i> If it is critical to obtain every active
929 * thread in the current thread's thread group and its subgroups, the
930 * invoker should verify that the returned int value is strictly less
931 * than the length of {@code tarray}.
933 * <p> Due to the inherent race condition in this method, it is recommended
934 * that the method only be used for debugging and monitoring purposes.
937 * an array into which to put the list of threads
939 * @return the number of threads put into the array
941 * @throws SecurityException
942 * if {@link java.lang.ThreadGroup#checkAccess} determines that
943 * the current thread cannot access its thread group
945 public static int enumerate(Thread tarray[]) {
946 throw new SecurityException();
950 * Counts the number of stack frames in this thread. The thread must
953 * @return the number of stack frames in this thread.
954 * @exception IllegalThreadStateException if this thread is not
956 * @deprecated The definition of this call depends on {@link #suspend},
957 * which is deprecated. Further, the results of this call
958 * were never well-defined.
961 public native int countStackFrames();
964 * Waits at most {@code millis} milliseconds for this thread to
965 * die. A timeout of {@code 0} means to wait forever.
967 * <p> This implementation uses a loop of {@code this.wait} calls
968 * conditioned on {@code this.isAlive}. As a thread terminates the
969 * {@code this.notifyAll} method is invoked. It is recommended that
970 * applications not use {@code wait}, {@code notify}, or
971 * {@code notifyAll} on {@code Thread} instances.
974 * the time to wait in milliseconds
976 * @throws IllegalArgumentException
977 * if the value of {@code millis} is negative
979 * @throws InterruptedException
980 * if any thread has interrupted the current thread. The
981 * <i>interrupted status</i> of the current thread is
982 * cleared when this exception is thrown.
984 public final synchronized void join(long millis)
985 throws InterruptedException {
986 long base = System.currentTimeMillis();
990 throw new IllegalArgumentException("timeout value is negative");
999 long delay = millis - now;
1004 now = System.currentTimeMillis() - base;
1010 * Waits at most {@code millis} milliseconds plus
1011 * {@code nanos} nanoseconds for this thread to die.
1013 * <p> This implementation uses a loop of {@code this.wait} calls
1014 * conditioned on {@code this.isAlive}. As a thread terminates the
1015 * {@code this.notifyAll} method is invoked. It is recommended that
1016 * applications not use {@code wait}, {@code notify}, or
1017 * {@code notifyAll} on {@code Thread} instances.
1020 * the time to wait in milliseconds
1023 * {@code 0-999999} additional nanoseconds to wait
1025 * @throws IllegalArgumentException
1026 * if the value of {@code millis} is negative, or the value
1027 * of {@code nanos} is not in the range {@code 0-999999}
1029 * @throws InterruptedException
1030 * if any thread has interrupted the current thread. The
1031 * <i>interrupted status</i> of the current thread is
1032 * cleared when this exception is thrown.
1034 public final synchronized void join(long millis, int nanos)
1035 throws InterruptedException {
1038 throw new IllegalArgumentException("timeout value is negative");
1041 if (nanos < 0 || nanos > 999999) {
1042 throw new IllegalArgumentException(
1043 "nanosecond timeout value out of range");
1046 if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
1054 * Waits for this thread to die.
1056 * <p> An invocation of this method behaves in exactly the same
1057 * way as the invocation
1060 * {@linkplain #join(long) join}{@code (0)}
1063 * @throws InterruptedException
1064 * if any thread has interrupted the current thread. The
1065 * <i>interrupted status</i> of the current thread is
1066 * cleared when this exception is thrown.
1068 public final void join() throws InterruptedException {
1073 * Prints a stack trace of the current thread to the standard error stream.
1074 * This method is used only for debugging.
1076 * @see Throwable#printStackTrace()
1078 public static void dumpStack() {
1079 new Exception("Stack trace").printStackTrace();
1083 * Marks this thread as either a {@linkplain #isDaemon daemon} thread
1084 * or a user thread. The Java Virtual Machine exits when the only
1085 * threads running are all daemon threads.
1087 * <p> This method must be invoked before the thread is started.
1090 * if {@code true}, marks this thread as a daemon thread
1092 * @throws IllegalThreadStateException
1093 * if this thread is {@linkplain #isAlive alive}
1095 * @throws SecurityException
1096 * if {@link #checkAccess} determines that the current
1097 * thread cannot modify this thread
1099 public final void setDaemon(boolean on) {
1100 throw new SecurityException();
1104 * Tests if this thread is a daemon thread.
1106 * @return <code>true</code> if this thread is a daemon thread;
1107 * <code>false</code> otherwise.
1108 * @see #setDaemon(boolean)
1110 public final boolean isDaemon() {
1115 * Determines if the currently running thread has permission to
1116 * modify this thread.
1118 * If there is a security manager, its <code>checkAccess</code> method
1119 * is called with this thread as its argument. This may result in
1120 * throwing a <code>SecurityException</code>.
1122 * @exception SecurityException if the current thread is not allowed to
1123 * access this thread.
1124 * @see SecurityManager#checkAccess(Thread)
1126 public final void checkAccess() {
1127 throw new SecurityException();
1131 * Returns a string representation of this thread, including the
1132 * thread's name, priority, and thread group.
1134 * @return a string representation of this thread.
1136 public String toString() {
1137 return "Thread[" + getName() + "," + getPriority() + "," +
1142 * Returns the context ClassLoader for this Thread. The context
1143 * ClassLoader is provided by the creator of the thread for use
1144 * by code running in this thread when loading classes and resources.
1145 * If not {@linkplain #setContextClassLoader set}, the default is the
1146 * ClassLoader context of the parent Thread. The context ClassLoader of the
1147 * primordial thread is typically set to the class loader used to load the
1150 * <p>If a security manager is present, and the invoker's class loader is not
1151 * {@code null} and is not the same as or an ancestor of the context class
1152 * loader, then this method invokes the security manager's {@link
1153 * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1154 * method with a {@link RuntimePermission RuntimePermission}{@code
1155 * ("getClassLoader")} permission to verify that retrieval of the context
1156 * class loader is permitted.
1158 * @return the context ClassLoader for this Thread, or {@code null}
1159 * indicating the system class loader (or, failing that, the
1160 * bootstrap class loader)
1162 * @throws SecurityException
1163 * if the current thread cannot get the context ClassLoader
1167 public ClassLoader getContextClassLoader() {
1168 return ClassLoader.getSystemClassLoader();
1172 * Sets the context ClassLoader for this Thread. The context
1173 * ClassLoader can be set when a thread is created, and allows
1174 * the creator of the thread to provide the appropriate class loader,
1175 * through {@code getContextClassLoader}, to code running in the thread
1176 * when loading classes and resources.
1178 * <p>If a security manager is present, its {@link
1179 * SecurityManager#checkPermission(java.security.Permission) checkPermission}
1180 * method is invoked with a {@link RuntimePermission RuntimePermission}{@code
1181 * ("setContextClassLoader")} permission to see if setting the context
1182 * ClassLoader is permitted.
1185 * the context ClassLoader for this Thread, or null indicating the
1186 * system class loader (or, failing that, the bootstrap class loader)
1188 * @throws SecurityException
1189 * if the current thread cannot set the context ClassLoader
1193 public void setContextClassLoader(ClassLoader cl) {
1194 if (cl == ClassLoader.getSystemClassLoader()) {
1197 throw new SecurityException();
1201 * Returns <tt>true</tt> if and only if the current thread holds the
1202 * monitor lock on the specified object.
1204 * <p>This method is designed to allow a program to assert that
1205 * the current thread already holds a specified lock:
1207 * assert Thread.holdsLock(obj);
1210 * @param obj the object on which to test lock ownership
1211 * @throws NullPointerException if obj is <tt>null</tt>
1212 * @return <tt>true</tt> if the current thread holds the monitor lock on
1213 * the specified object.
1216 public static boolean holdsLock(Object obj) {
1221 * Returns an array of stack trace elements representing the stack dump
1222 * of this thread. This method will return a zero-length array if
1223 * this thread has not started, has started but has not yet been
1224 * scheduled to run by the system, or has terminated.
1225 * If the returned array is of non-zero length then the first element of
1226 * the array represents the top of the stack, which is the most recent
1227 * method invocation in the sequence. The last element of the array
1228 * represents the bottom of the stack, which is the least recent method
1229 * invocation in the sequence.
1231 * <p>If there is a security manager, and this thread is not
1232 * the current thread, then the security manager's
1233 * <tt>checkPermission</tt> method is called with a
1234 * <tt>RuntimePermission("getStackTrace")</tt> permission
1235 * to see if it's ok to get the stack trace.
1237 * <p>Some virtual machines may, under some circumstances, omit one
1238 * or more stack frames from the stack trace. In the extreme case,
1239 * a virtual machine that has no stack trace information concerning
1240 * this thread is permitted to return a zero-length array from this
1243 * @return an array of <tt>StackTraceElement</tt>,
1244 * each represents one stack frame.
1246 * @throws SecurityException
1247 * if a security manager exists and its
1248 * <tt>checkPermission</tt> method doesn't allow
1249 * getting the stack trace of thread.
1250 * @see SecurityManager#checkPermission
1251 * @see RuntimePermission
1252 * @see Throwable#getStackTrace
1256 public StackTraceElement[] getStackTrace() {
1257 throw new SecurityException();
1261 * Returns a map of stack traces for all live threads.
1262 * The map keys are threads and each map value is an array of
1263 * <tt>StackTraceElement</tt> that represents the stack dump
1264 * of the corresponding <tt>Thread</tt>.
1265 * The returned stack traces are in the format specified for
1266 * the {@link #getStackTrace getStackTrace} method.
1268 * <p>The threads may be executing while this method is called.
1269 * The stack trace of each thread only represents a snapshot and
1270 * each stack trace may be obtained at different time. A zero-length
1271 * array will be returned in the map value if the virtual machine has
1272 * no stack trace information about a thread.
1274 * <p>If there is a security manager, then the security manager's
1275 * <tt>checkPermission</tt> method is called with a
1276 * <tt>RuntimePermission("getStackTrace")</tt> permission as well as
1277 * <tt>RuntimePermission("modifyThreadGroup")</tt> permission
1278 * to see if it is ok to get the stack trace of all threads.
1280 * @return a <tt>Map</tt> from <tt>Thread</tt> to an array of
1281 * <tt>StackTraceElement</tt> that represents the stack trace of
1282 * the corresponding thread.
1284 * @throws SecurityException
1285 * if a security manager exists and its
1286 * <tt>checkPermission</tt> method doesn't allow
1287 * getting the stack trace of thread.
1288 * @see #getStackTrace
1289 * @see SecurityManager#checkPermission
1290 * @see RuntimePermission
1291 * @see Throwable#getStackTrace
1295 public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
1296 throw new SecurityException();
1300 * Returns the identifier of this Thread. The thread ID is a positive
1301 * <tt>long</tt> number generated when this thread was created.
1302 * The thread ID is unique and remains unchanged during its lifetime.
1303 * When a thread is terminated, this thread ID may be reused.
1305 * @return this thread's ID.
1308 public long getId() {
1313 * A thread state. A thread can be in one of the following states:
1315 * <li>{@link #NEW}<br>
1316 * A thread that has not yet started is in this state.
1318 * <li>{@link #RUNNABLE}<br>
1319 * A thread executing in the Java virtual machine is in this state.
1321 * <li>{@link #BLOCKED}<br>
1322 * A thread that is blocked waiting for a monitor lock
1325 * <li>{@link #WAITING}<br>
1326 * A thread that is waiting indefinitely for another thread to
1327 * perform a particular action is in this state.
1329 * <li>{@link #TIMED_WAITING}<br>
1330 * A thread that is waiting for another thread to perform an action
1331 * for up to a specified waiting time is in this state.
1333 * <li>{@link #TERMINATED}<br>
1334 * A thread that has exited is in this state.
1339 * A thread can be in only one state at a given point in time.
1340 * These states are virtual machine states which do not reflect
1341 * any operating system thread states.
1348 * Thread state for a thread which has not yet started.
1353 * Thread state for a runnable thread. A thread in the runnable
1354 * state is executing in the Java virtual machine but it may
1355 * be waiting for other resources from the operating system
1356 * such as processor.
1361 * Thread state for a thread blocked waiting for a monitor lock.
1362 * A thread in the blocked state is waiting for a monitor lock
1363 * to enter a synchronized block/method or
1364 * reenter a synchronized block/method after calling
1365 * {@link Object#wait() Object.wait}.
1370 * Thread state for a waiting thread.
1371 * A thread is in the waiting state due to calling one of the
1372 * following methods:
1374 * <li>{@link Object#wait() Object.wait} with no timeout</li>
1375 * <li>{@link #join() Thread.join} with no timeout</li>
1376 * <li>{@link LockSupport#park() LockSupport.park}</li>
1379 * <p>A thread in the waiting state is waiting for another thread to
1380 * perform a particular action.
1382 * For example, a thread that has called <tt>Object.wait()</tt>
1383 * on an object is waiting for another thread to call
1384 * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
1385 * that object. A thread that has called <tt>Thread.join()</tt>
1386 * is waiting for a specified thread to terminate.
1391 * Thread state for a waiting thread with a specified waiting time.
1392 * A thread is in the timed waiting state due to calling one of
1393 * the following methods with a specified positive waiting time:
1395 * <li>{@link #sleep Thread.sleep}</li>
1396 * <li>{@link Object#wait(long) Object.wait} with timeout</li>
1397 * <li>{@link #join(long) Thread.join} with timeout</li>
1398 * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
1399 * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
1405 * Thread state for a terminated thread.
1406 * The thread has completed execution.
1412 * Returns the state of this thread.
1413 * This method is designed for use in monitoring of the system state,
1414 * not for synchronization control.
1416 * @return this thread's state.
1419 public State getState() {
1420 // get current thread state
1421 return State.RUNNABLE;
1427 * Interface for handlers invoked when a <tt>Thread</tt> abruptly
1428 * terminates due to an uncaught exception.
1429 * <p>When a thread is about to terminate due to an uncaught exception
1430 * the Java Virtual Machine will query the thread for its
1431 * <tt>UncaughtExceptionHandler</tt> using
1432 * {@link #getUncaughtExceptionHandler} and will invoke the handler's
1433 * <tt>uncaughtException</tt> method, passing the thread and the
1434 * exception as arguments.
1435 * If a thread has not had its <tt>UncaughtExceptionHandler</tt>
1436 * explicitly set, then its <tt>ThreadGroup</tt> object acts as its
1437 * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object
1439 * special requirements for dealing with the exception, it can forward
1440 * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
1441 * default uncaught exception handler}.
1443 * @see #setDefaultUncaughtExceptionHandler
1444 * @see #setUncaughtExceptionHandler
1445 * @see ThreadGroup#uncaughtException
1448 public interface UncaughtExceptionHandler {
1450 * Method invoked when the given thread terminates due to the
1451 * given uncaught exception.
1452 * <p>Any exception thrown by this method will be ignored by the
1453 * Java Virtual Machine.
1454 * @param t the thread
1455 * @param e the exception
1457 void uncaughtException(Thread t, Throwable e);
1460 // null unless explicitly set
1461 private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
1463 // null unless explicitly set
1464 private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
1467 * Set the default handler invoked when a thread abruptly terminates
1468 * due to an uncaught exception, and no other handler has been defined
1471 * <p>Uncaught exception handling is controlled first by the thread, then
1472 * by the thread's {@link ThreadGroup} object and finally by the default
1473 * uncaught exception handler. If the thread does not have an explicit
1474 * uncaught exception handler set, and the thread's thread group
1475 * (including parent thread groups) does not specialize its
1476 * <tt>uncaughtException</tt> method, then the default handler's
1477 * <tt>uncaughtException</tt> method will be invoked.
1478 * <p>By setting the default uncaught exception handler, an application
1479 * can change the way in which uncaught exceptions are handled (such as
1480 * logging to a specific device, or file) for those threads that would
1481 * already accept whatever "default" behavior the system
1484 * <p>Note that the default uncaught exception handler should not usually
1485 * defer to the thread's <tt>ThreadGroup</tt> object, as that could cause
1486 * infinite recursion.
1488 * @param eh the object to use as the default uncaught exception handler.
1489 * If <tt>null</tt> then there is no default handler.
1491 * @throws SecurityException if a security manager is present and it
1492 * denies <tt>{@link RuntimePermission}
1493 * ("setDefaultUncaughtExceptionHandler")</tt>
1495 * @see #setUncaughtExceptionHandler
1496 * @see #getUncaughtExceptionHandler
1497 * @see ThreadGroup#uncaughtException
1500 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1501 throw new SecurityException();
1505 * Returns the default handler invoked when a thread abruptly terminates
1506 * due to an uncaught exception. If the returned value is <tt>null</tt>,
1507 * there is no default.
1509 * @see #setDefaultUncaughtExceptionHandler
1511 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
1512 return defaultUncaughtExceptionHandler;
1516 * Returns the handler invoked when this thread abruptly terminates
1517 * due to an uncaught exception. If this thread has not had an
1518 * uncaught exception handler explicitly set then this thread's
1519 * <tt>ThreadGroup</tt> object is returned, unless this thread
1520 * has terminated, in which case <tt>null</tt> is returned.
1523 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
1524 return uncaughtExceptionHandler != null ?
1525 uncaughtExceptionHandler : null;
1529 * Set the handler invoked when this thread abruptly terminates
1530 * due to an uncaught exception.
1531 * <p>A thread can take full control of how it responds to uncaught
1532 * exceptions by having its uncaught exception handler explicitly set.
1533 * If no such handler is set then the thread's <tt>ThreadGroup</tt>
1534 * object acts as its handler.
1535 * @param eh the object to use as this thread's uncaught exception
1536 * handler. If <tt>null</tt> then this thread has no explicit handler.
1537 * @throws SecurityException if the current thread is not allowed to
1538 * modify this thread.
1539 * @see #setDefaultUncaughtExceptionHandler
1540 * @see ThreadGroup#uncaughtException
1543 public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
1545 uncaughtExceptionHandler = eh;