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