rt/emul/compact/src/main/java/java/lang/Thread.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 31 Oct 2013 15:16:56 +0100
changeset 1403 8120793cc756
parent 1260 fe3567c7b522
permissions -rw-r--r--
Allow idempotent setting of system classloader
     1 /*
     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.
     4  *
     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.
    10  *
    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).
    16  *
    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.
    20  *
    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
    23  * questions.
    24  */
    25 
    26 package java.lang;
    27 
    28 import java.util.Map;
    29 
    30 
    31 /**
    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.
    35  * <p>
    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.
    43  * <p>
    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
    48  * occurs:
    49  * <ul>
    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
    52  *     to take place.
    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>
    56  *     method.
    57  * </ul>
    58  * <p>
    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 {
    67  *         long minPrime;
    68  *         PrimeThread(long minPrime) {
    69  *             this.minPrime = minPrime;
    70  *         }
    71  *
    72  *         public void run() {
    73  *             // compute primes larger than minPrime
    74  *             &nbsp;.&nbsp;.&nbsp;.
    75  *         }
    76  *     }
    77  * </pre></blockquote><hr>
    78  * <p>
    79  * The following code would then create a thread and start it running:
    80  * <p><blockquote><pre>
    81  *     PrimeThread p = new PrimeThread(143);
    82  *     p.start();
    83  * </pre></blockquote>
    84  * <p>
    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 {
    93  *         long minPrime;
    94  *         PrimeRun(long minPrime) {
    95  *             this.minPrime = minPrime;
    96  *         }
    97  *
    98  *         public void run() {
    99  *             // compute primes larger than minPrime
   100  *             &nbsp;.&nbsp;.&nbsp;.
   101  *         }
   102  *     }
   103  * </pre></blockquote><hr>
   104  * <p>
   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>
   110  * <p>
   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.
   114  * <p>
   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
   117  * thrown.
   118  *
   119  * @author  unascribed
   120  * @see     Runnable
   121  * @see     Runtime#exit(int)
   122  * @see     #run()
   123  * @see     #stop()
   124  * @since   JDK1.0
   125  */
   126 public
   127 class Thread implements Runnable {
   128 
   129     /**
   130      * The minimum priority that a thread can have.
   131      */
   132     public final static int MIN_PRIORITY = 1;
   133 
   134    /**
   135      * The default priority that is assigned to a thread.
   136      */
   137     public final static int NORM_PRIORITY = 5;
   138 
   139     /**
   140      * The maximum priority that a thread can have.
   141      */
   142     public final static int MAX_PRIORITY = 10;
   143 
   144     private static final Thread ONE = new Thread("main");
   145     /**
   146      * Returns a reference to the currently executing thread object.
   147      *
   148      * @return  the currently executing thread.
   149      */
   150     public static Thread currentThread() {
   151         return ONE;
   152     }
   153 
   154     /**
   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
   157      * hint.
   158      *
   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.
   163      *
   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.
   169      */
   170     public static void yield() {
   171     }
   172 
   173     /**
   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.
   178      *
   179      * @param  millis
   180      *         the length of time to sleep in milliseconds
   181      *
   182      * @throws  IllegalArgumentException
   183      *          if the value of {@code millis} is negative
   184      *
   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.
   189      */
   190     public static native void sleep(long millis) throws InterruptedException;
   191 
   192     /**
   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
   197      * monitors.
   198      *
   199      * @param  millis
   200      *         the length of time to sleep in milliseconds
   201      *
   202      * @param  nanos
   203      *         {@code 0-999999} additional nanoseconds to sleep
   204      *
   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}
   208      *
   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.
   213      */
   214     public static void sleep(long millis, int nanos)
   215     throws InterruptedException {
   216         if (millis < 0) {
   217             throw new IllegalArgumentException("timeout value is negative");
   218         }
   219 
   220         if (nanos < 0 || nanos > 999999) {
   221             throw new IllegalArgumentException(
   222                                 "nanosecond timeout value out of range");
   223         }
   224 
   225         if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
   226             millis++;
   227         }
   228 
   229         sleep(millis);
   230     }
   231     private Runnable target;
   232     private String name;
   233 
   234     /**
   235      * Throws CloneNotSupportedException as a Thread can not be meaningfully
   236      * cloned. Construct a new Thread instead.
   237      *
   238      * @throws  CloneNotSupportedException
   239      *          always
   240      */
   241     @Override
   242     protected Object clone() throws CloneNotSupportedException {
   243         throw new CloneNotSupportedException();
   244     }
   245 
   246     /**
   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.
   252      */
   253     public Thread() {
   254         init(null, null, "Thread-" + nextThreadNum(), 0);
   255     }
   256     
   257     private static int nextThreadNum() {
   258         return -1;
   259     }
   260 
   261     /**
   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.
   267      *
   268      * @param  target
   269      *         the object whose {@code run} method is invoked when this thread
   270      *         is started. If {@code null}, this classes {@code run} method does
   271      *         nothing.
   272      */
   273     public Thread(Runnable target) {
   274         init(null, target, "Thread-" + nextThreadNum(), 0);
   275     }
   276 
   277     /**
   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.
   283      *
   284      * @param  group
   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.
   291      *
   292      * @param  target
   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.
   295      *
   296      * @throws  SecurityException
   297      *          if the current thread cannot create a thread in the specified
   298      *          thread group
   299      */
   300 //    public Thread(ThreadGroup group, Runnable target) {
   301 //        init(group, target, "Thread-" + nextThreadNum(), 0);
   302 //    }
   303 
   304     /**
   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)}.
   308      *
   309      * @param   name
   310      *          the name of the new thread
   311      */
   312     public Thread(String name) {
   313         init(null, null, name, 0);
   314     }
   315     
   316     private void init(Object o1, Runnable trgt, String nm, int i4) {
   317         this.target = trgt;
   318         this.name = nm;
   319     }
   320 
   321     /**
   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)}.
   325      *
   326      * @param  group
   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.
   333      *
   334      * @param  name
   335      *         the name of the new thread
   336      *
   337      * @throws  SecurityException
   338      *          if the current thread cannot create a thread in the specified
   339      *          thread group
   340      */
   341 //    public Thread(ThreadGroup group, String name) {
   342 //        init(group, null, name, 0);
   343 //    }
   344 
   345     /**
   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)}.
   349      *
   350      * @param  target
   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.
   353      *
   354      * @param  name
   355      *         the name of the new thread
   356      */
   357     public Thread(Runnable target, String name) {
   358         init(null, target, name, 0);
   359     }
   360 
   361     /**
   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}.
   365      *
   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.
   369      *
   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.
   375      *
   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.
   380      *
   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.
   385      *
   386      * @param  group
   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.
   393      *
   394      * @param  target
   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.
   397      *
   398      * @param  name
   399      *         the name of the new thread
   400      *
   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.
   404      */
   405 //    public Thread(ThreadGroup group, Runnable target, String name) {
   406 //        init(group, target, name, 0);
   407 //    }
   408 
   409     /**
   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>.
   414      *
   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>
   421      *
   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>
   432      *
   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).
   440      *
   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.
   444      *
   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>
   452      *
   453      * <p>Implementation note: Java platform implementers are encouraged to
   454      * document their implementation's behavior with respect to the
   455      * {@code stackSize} parameter.
   456      *
   457      *
   458      * @param  group
   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.
   465      *
   466      * @param  target
   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.
   469      *
   470      * @param  name
   471      *         the name of the new thread
   472      *
   473      * @param  stackSize
   474      *         the desired stack size for the new thread, or zero to indicate
   475      *         that this parameter is to be ignored.
   476      *
   477      * @throws  SecurityException
   478      *          if the current thread cannot create a thread in the specified
   479      *          thread group
   480      *
   481      * @since 1.4
   482      */
   483 //    public Thread(ThreadGroup group, Runnable target, String name,
   484 //                  long stackSize) {
   485 //        init(group, target, name, stackSize);
   486 //    }
   487 
   488     /**
   489      * Causes this thread to begin execution; the Java Virtual Machine
   490      * calls the <code>run</code> method of this thread.
   491      * <p>
   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).
   496      * <p>
   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
   499      * execution.
   500      *
   501      * @exception  IllegalThreadStateException  if the thread was already
   502      *               started.
   503      * @see        #run()
   504      * @see        #stop()
   505      */
   506     public void start() {
   507         throw new SecurityException();
   508     }
   509 
   510     /**
   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.
   515      * <p>
   516      * Subclasses of <code>Thread</code> should override this method.
   517      *
   518      * @see     #start()
   519      * @see     #stop()
   520      * @see     #Thread(ThreadGroup, Runnable, String)
   521      */
   522     @Override
   523     public void run() {
   524         if (target != null) {
   525             target.run();
   526         }
   527     }
   528 
   529     /**
   530      * Forces the thread to stop executing.
   531      * <p>
   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).
   536      * <p>
   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
   541      * addition.
   542      * Again, this may result in throwing a
   543      * <code>SecurityException</code> (in the current thread).
   544      * <p>
   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.
   548      * <p>
   549      * It is permitted to stop a thread that has not yet been started.
   550      * If the thread is eventually started, it immediately terminates.
   551      * <p>
   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.
   560      * <p>
   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>.
   565      *
   566      * @exception  SecurityException  if the current thread cannot
   567      *               modify this thread.
   568      * @see        #interrupt()
   569      * @see        #checkAccess()
   570      * @see        #run()
   571      * @see        #start()
   572      * @see        ThreadDeath
   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>.
   594      */
   595     @Deprecated
   596     public final void stop() {
   597         stop(null);
   598     }
   599 
   600     /**
   601      * Forces the thread to stop executing.
   602      * <p>
   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).
   606      * <p>
   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
   612      * addition.
   613      * Again, this may result in throwing a
   614      * <code>SecurityException</code> (in the current thread).
   615      * <p>
   616      * If the argument <code>obj</code> is null, a
   617      * <code>NullPointerException</code> is thrown (in the current thread).
   618      * <p>
   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.
   624      * <p>
   625      * It is permitted to stop a thread that has not yet been started.
   626      * If the thread is eventually started, it immediately terminates.
   627      *
   628      * @param      obj   the Throwable object to be thrown.
   629      * @exception  SecurityException  if the current thread cannot modify
   630      *               this thread.
   631      * @throws     NullPointerException if obj is <tt>null</tt>.
   632      * @see        #interrupt()
   633      * @see        #checkAccess()
   634      * @see        #run()
   635      * @see        #start()
   636      * @see        #stop()
   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>.
   648      */
   649     @Deprecated
   650     public final synchronized void stop(Throwable obj) {
   651         throw new SecurityException();
   652     }
   653 
   654     /**
   655      * Interrupts this thread.
   656      *
   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.
   661      *
   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}.
   669      *
   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}.
   675      *
   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.
   681      *
   682      * <p> If none of the previous conditions hold then this thread's interrupt
   683      * status will be set. </p>
   684      *
   685      * <p> Interrupting a thread that is not alive need not have any effect.
   686      *
   687      * @throws  SecurityException
   688      *          if the current thread cannot modify this thread
   689      *
   690      * @revised 6.0
   691      * @spec JSR-51
   692      */
   693     public void interrupt() {
   694         throw new SecurityException();
   695     }
   696 
   697     /**
   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).
   704      *
   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
   707      * returning false.
   708      *
   709      * @return  <code>true</code> if the current thread has been interrupted;
   710      *          <code>false</code> otherwise.
   711      * @see #isInterrupted()
   712      * @revised 6.0
   713      */
   714     public static boolean interrupted() {
   715         return currentThread().isInterrupted();
   716     }
   717 
   718     /**
   719      * Tests whether this thread has been interrupted.  The <i>interrupted
   720      * status</i> of the thread is unaffected by this method.
   721      *
   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
   724      * returning false.
   725      *
   726      * @return  <code>true</code> if this thread has been interrupted;
   727      *          <code>false</code> otherwise.
   728      * @see     #interrupted()
   729      * @revised 6.0
   730      */
   731     public boolean isInterrupted() {
   732         return false;
   733     }
   734 
   735     /**
   736      * Throws {@link NoSuchMethodError}.
   737      *
   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
   751      */
   752     @Deprecated
   753     public void destroy() {
   754         throw new SecurityException();
   755     }
   756 
   757     /**
   758      * Tests if this thread is alive. A thread is alive if it has
   759      * been started and has not yet died.
   760      *
   761      * @return  <code>true</code> if this thread is alive;
   762      *          <code>false</code> otherwise.
   763      */
   764     public final boolean isAlive() {
   765         return true;
   766     }
   767 
   768     /**
   769      * Suspends this thread.
   770      * <p>
   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).
   774      * <p>
   775      * If the thread is alive, it is suspended and makes no further
   776      * progress unless and until it is resumed.
   777      *
   778      * @exception  SecurityException  if the current thread cannot modify
   779      *               this thread.
   780      * @see #checkAccess
   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>.
   791      */
   792     @Deprecated
   793     public final void suspend() {
   794         checkAccess();
   795     }
   796 
   797     /**
   798      * Resumes a suspended thread.
   799      * <p>
   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).
   803      * <p>
   804      * If the thread is alive but suspended, it is resumed and is
   805      * permitted to make progress in its execution.
   806      *
   807      * @exception  SecurityException  if the current thread cannot modify this
   808      *               thread.
   809      * @see        #checkAccess
   810      * @see        #suspend()
   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>.
   816      */
   817     @Deprecated
   818     public final void resume() {
   819         checkAccess();
   820     }
   821 
   822     /**
   823      * Changes the priority of this thread.
   824      * <p>
   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>.
   828      * <p>
   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.
   832      *
   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
   838      *               this thread.
   839      * @see        #getPriority
   840      * @see        #checkAccess()
   841      * @see        #getThreadGroup()
   842      * @see        #MAX_PRIORITY
   843      * @see        #MIN_PRIORITY
   844      * @see        ThreadGroup#getMaxPriority()
   845      */
   846     public final void setPriority(int newPriority) {
   847         throw new SecurityException();
   848     }
   849 
   850     /**
   851      * Returns this thread's priority.
   852      *
   853      * @return  this thread's priority.
   854      * @see     #setPriority
   855      */
   856     public final int getPriority() {
   857         return Thread.NORM_PRIORITY;
   858     }
   859 
   860     /**
   861      * Changes the name of this thread to be equal to the argument
   862      * <code>name</code>.
   863      * <p>
   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>.
   867      *
   868      * @param      name   the new name for this thread.
   869      * @exception  SecurityException  if the current thread cannot modify this
   870      *               thread.
   871      * @see        #getName
   872      * @see        #checkAccess()
   873      */
   874     public final void setName(String name) {
   875         throw new SecurityException();
   876     }
   877 
   878     /**
   879      * Returns this thread's name.
   880      *
   881      * @return  this thread's name.
   882      * @see     #setName(String)
   883      */
   884     public final String getName() {
   885         return String.valueOf(name);
   886     }
   887 
   888     /**
   889      * Returns the thread group to which this thread belongs.
   890      * This method returns null if this thread has died
   891      * (been stopped).
   892      *
   893      * @return  this thread's thread group.
   894      */
   895 //    public final ThreadGroup getThreadGroup() {
   896 //        return group;
   897 //    }
   898 
   899     /**
   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.
   904      *
   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.
   910      *
   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
   914      */
   915     public static int activeCount() {
   916         return 1;
   917     }
   918 
   919     /**
   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.
   924      *
   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}.
   932      *
   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.
   935      *
   936      * @param  tarray
   937      *         an array into which to put the list of threads
   938      *
   939      * @return  the number of threads put into the array
   940      *
   941      * @throws  SecurityException
   942      *          if {@link java.lang.ThreadGroup#checkAccess} determines that
   943      *          the current thread cannot access its thread group
   944      */
   945     public static int enumerate(Thread tarray[]) {
   946         throw new SecurityException();
   947     }
   948 
   949     /**
   950      * Counts the number of stack frames in this thread. The thread must
   951      * be suspended.
   952      *
   953      * @return     the number of stack frames in this thread.
   954      * @exception  IllegalThreadStateException  if this thread is not
   955      *             suspended.
   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.
   959      */
   960     @Deprecated
   961     public native int countStackFrames();
   962 
   963     /**
   964      * Waits at most {@code millis} milliseconds for this thread to
   965      * die. A timeout of {@code 0} means to wait forever.
   966      *
   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.
   972      *
   973      * @param  millis
   974      *         the time to wait in milliseconds
   975      *
   976      * @throws  IllegalArgumentException
   977      *          if the value of {@code millis} is negative
   978      *
   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.
   983      */
   984     public final synchronized void join(long millis)
   985     throws InterruptedException {
   986         long base = System.currentTimeMillis();
   987         long now = 0;
   988 
   989         if (millis < 0) {
   990             throw new IllegalArgumentException("timeout value is negative");
   991         }
   992 
   993         if (millis == 0) {
   994             while (isAlive()) {
   995                 wait(0);
   996             }
   997         } else {
   998             while (isAlive()) {
   999                 long delay = millis - now;
  1000                 if (delay <= 0) {
  1001                     break;
  1002                 }
  1003                 wait(delay);
  1004                 now = System.currentTimeMillis() - base;
  1005             }
  1006         }
  1007     }
  1008 
  1009     /**
  1010      * Waits at most {@code millis} milliseconds plus
  1011      * {@code nanos} nanoseconds for this thread to die.
  1012      *
  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.
  1018      *
  1019      * @param  millis
  1020      *         the time to wait in milliseconds
  1021      *
  1022      * @param  nanos
  1023      *         {@code 0-999999} additional nanoseconds to wait
  1024      *
  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}
  1028      *
  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.
  1033      */
  1034     public final synchronized void join(long millis, int nanos)
  1035     throws InterruptedException {
  1036 
  1037         if (millis < 0) {
  1038             throw new IllegalArgumentException("timeout value is negative");
  1039         }
  1040 
  1041         if (nanos < 0 || nanos > 999999) {
  1042             throw new IllegalArgumentException(
  1043                                 "nanosecond timeout value out of range");
  1044         }
  1045 
  1046         if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  1047             millis++;
  1048         }
  1049 
  1050         join(millis);
  1051     }
  1052 
  1053     /**
  1054      * Waits for this thread to die.
  1055      *
  1056      * <p> An invocation of this method behaves in exactly the same
  1057      * way as the invocation
  1058      *
  1059      * <blockquote>
  1060      * {@linkplain #join(long) join}{@code (0)}
  1061      * </blockquote>
  1062      *
  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.
  1067      */
  1068     public final void join() throws InterruptedException {
  1069         join(0);
  1070     }
  1071 
  1072     /**
  1073      * Prints a stack trace of the current thread to the standard error stream.
  1074      * This method is used only for debugging.
  1075      *
  1076      * @see     Throwable#printStackTrace()
  1077      */
  1078     public static void dumpStack() {
  1079         new Exception("Stack trace").printStackTrace();
  1080     }
  1081 
  1082     /**
  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.
  1086      *
  1087      * <p> This method must be invoked before the thread is started.
  1088      *
  1089      * @param  on
  1090      *         if {@code true}, marks this thread as a daemon thread
  1091      *
  1092      * @throws  IllegalThreadStateException
  1093      *          if this thread is {@linkplain #isAlive alive}
  1094      *
  1095      * @throws  SecurityException
  1096      *          if {@link #checkAccess} determines that the current
  1097      *          thread cannot modify this thread
  1098      */
  1099     public final void setDaemon(boolean on) {
  1100         throw new SecurityException();
  1101     }
  1102 
  1103     /**
  1104      * Tests if this thread is a daemon thread.
  1105      *
  1106      * @return  <code>true</code> if this thread is a daemon thread;
  1107      *          <code>false</code> otherwise.
  1108      * @see     #setDaemon(boolean)
  1109      */
  1110     public final boolean isDaemon() {
  1111         return false;
  1112     }
  1113 
  1114     /**
  1115      * Determines if the currently running thread has permission to
  1116      * modify this thread.
  1117      * <p>
  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>.
  1121      *
  1122      * @exception  SecurityException  if the current thread is not allowed to
  1123      *               access this thread.
  1124      * @see        SecurityManager#checkAccess(Thread)
  1125      */
  1126     public final void checkAccess() {
  1127         throw new SecurityException();
  1128     }
  1129 
  1130     /**
  1131      * Returns a string representation of this thread, including the
  1132      * thread's name, priority, and thread group.
  1133      *
  1134      * @return  a string representation of this thread.
  1135      */
  1136     public String toString() {
  1137         return "Thread[" + getName() + "," + getPriority() + "," +
  1138                         "" + "]";
  1139     }
  1140 
  1141     /**
  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
  1148      * application.
  1149      *
  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.
  1157      *
  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)
  1161      *
  1162      * @throws  SecurityException
  1163      *          if the current thread cannot get the context ClassLoader
  1164      *
  1165      * @since 1.2
  1166      */
  1167     public ClassLoader getContextClassLoader() {
  1168         return ClassLoader.getSystemClassLoader();
  1169     }
  1170 
  1171     /**
  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.
  1177      *
  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.
  1183      *
  1184      * @param  cl
  1185      *         the context ClassLoader for this Thread, or null  indicating the
  1186      *         system class loader (or, failing that, the bootstrap class loader)
  1187      *
  1188      * @throws  SecurityException
  1189      *          if the current thread cannot set the context ClassLoader
  1190      *
  1191      * @since 1.2
  1192      */
  1193     public void setContextClassLoader(ClassLoader cl) {
  1194         if (cl == ClassLoader.getSystemClassLoader()) {
  1195             return;
  1196         }
  1197         throw new SecurityException();
  1198     }
  1199 
  1200     /**
  1201      * Returns <tt>true</tt> if and only if the current thread holds the
  1202      * monitor lock on the specified object.
  1203      *
  1204      * <p>This method is designed to allow a program to assert that
  1205      * the current thread already holds a specified lock:
  1206      * <pre>
  1207      *     assert Thread.holdsLock(obj);
  1208      * </pre>
  1209      *
  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.
  1214      * @since 1.4
  1215      */
  1216     public static boolean holdsLock(Object obj) {
  1217         return true;
  1218     }
  1219 
  1220     /**
  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.
  1230      *
  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.
  1236      *
  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
  1241      * method.
  1242      *
  1243      * @return an array of <tt>StackTraceElement</tt>,
  1244      * each represents one stack frame.
  1245      *
  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
  1253      *
  1254      * @since 1.5
  1255      */
  1256     public StackTraceElement[] getStackTrace() {
  1257         throw new SecurityException();
  1258     }
  1259 
  1260     /**
  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.
  1267      *
  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.
  1273      *
  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.
  1279      *
  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.
  1283      *
  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
  1292      *
  1293      * @since 1.5
  1294      */
  1295     public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
  1296         throw new SecurityException();
  1297     }
  1298 
  1299     /**
  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.
  1304      *
  1305      * @return this thread's ID.
  1306      * @since 1.5
  1307      */
  1308     public long getId() {
  1309         return 0;
  1310     }
  1311 
  1312     /**
  1313      * A thread state.  A thread can be in one of the following states:
  1314      * <ul>
  1315      * <li>{@link #NEW}<br>
  1316      *     A thread that has not yet started is in this state.
  1317      *     </li>
  1318      * <li>{@link #RUNNABLE}<br>
  1319      *     A thread executing in the Java virtual machine is in this state.
  1320      *     </li>
  1321      * <li>{@link #BLOCKED}<br>
  1322      *     A thread that is blocked waiting for a monitor lock
  1323      *     is in this state.
  1324      *     </li>
  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.
  1328      *     </li>
  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.
  1332      *     </li>
  1333      * <li>{@link #TERMINATED}<br>
  1334      *     A thread that has exited is in this state.
  1335      *     </li>
  1336      * </ul>
  1337      *
  1338      * <p>
  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.
  1342      *
  1343      * @since   1.5
  1344      * @see #getState
  1345      */
  1346     public enum State {
  1347         /**
  1348          * Thread state for a thread which has not yet started.
  1349          */
  1350         NEW,
  1351 
  1352         /**
  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.
  1357          */
  1358         RUNNABLE,
  1359 
  1360         /**
  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}.
  1366          */
  1367         BLOCKED,
  1368 
  1369         /**
  1370          * Thread state for a waiting thread.
  1371          * A thread is in the waiting state due to calling one of the
  1372          * following methods:
  1373          * <ul>
  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>
  1377          * </ul>
  1378          *
  1379          * <p>A thread in the waiting state is waiting for another thread to
  1380          * perform a particular action.
  1381          *
  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.
  1387          */
  1388         WAITING,
  1389 
  1390         /**
  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:
  1394          * <ul>
  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>
  1400          * </ul>
  1401          */
  1402         TIMED_WAITING,
  1403 
  1404         /**
  1405          * Thread state for a terminated thread.
  1406          * The thread has completed execution.
  1407          */
  1408         TERMINATED;
  1409     }
  1410 
  1411     /**
  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.
  1415      *
  1416      * @return this thread's state.
  1417      * @since 1.5
  1418      */
  1419     public State getState() {
  1420         // get current thread state
  1421         return State.RUNNABLE;
  1422     }
  1423 
  1424     // Added in JSR-166
  1425 
  1426     /**
  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
  1438      * has no
  1439      * special requirements for dealing with the exception, it can forward
  1440      * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
  1441      * default uncaught exception handler}.
  1442      *
  1443      * @see #setDefaultUncaughtExceptionHandler
  1444      * @see #setUncaughtExceptionHandler
  1445      * @see ThreadGroup#uncaughtException
  1446      * @since 1.5
  1447      */
  1448     public interface UncaughtExceptionHandler {
  1449         /**
  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
  1456          */
  1457         void uncaughtException(Thread t, Throwable e);
  1458     }
  1459 
  1460     // null unless explicitly set
  1461     private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
  1462 
  1463     // null unless explicitly set
  1464     private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
  1465 
  1466     /**
  1467      * Set the default handler invoked when a thread abruptly terminates
  1468      * due to an uncaught exception, and no other handler has been defined
  1469      * for that thread.
  1470      *
  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 &quot;default&quot; behavior the system
  1482      * provided.
  1483      *
  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.
  1487      *
  1488      * @param eh the object to use as the default uncaught exception handler.
  1489      * If <tt>null</tt> then there is no default handler.
  1490      *
  1491      * @throws SecurityException if a security manager is present and it
  1492      *         denies <tt>{@link RuntimePermission}
  1493      *         (&quot;setDefaultUncaughtExceptionHandler&quot;)</tt>
  1494      *
  1495      * @see #setUncaughtExceptionHandler
  1496      * @see #getUncaughtExceptionHandler
  1497      * @see ThreadGroup#uncaughtException
  1498      * @since 1.5
  1499      */
  1500     public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
  1501         throw new SecurityException();
  1502     }
  1503 
  1504     /**
  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.
  1508      * @since 1.5
  1509      * @see #setDefaultUncaughtExceptionHandler
  1510      */
  1511     public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
  1512         return defaultUncaughtExceptionHandler;
  1513     }
  1514 
  1515     /**
  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.
  1521      * @since 1.5
  1522      */
  1523     public UncaughtExceptionHandler getUncaughtExceptionHandler() {
  1524         return uncaughtExceptionHandler != null ?
  1525             uncaughtExceptionHandler : null;
  1526     }
  1527 
  1528     /**
  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
  1541      * @since 1.5
  1542      */
  1543     public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
  1544         checkAccess();
  1545         uncaughtExceptionHandler = eh;
  1546     }
  1547 }