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