Source for java.lang.Thread

   1: /* Thread -- an independent thread of executable code
   2:    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
   3:    Free Software Foundation
   4: 
   5: This file is part of GNU Classpath.
   6: 
   7: GNU Classpath is free software; you can redistribute it and/or modify
   8: it under the terms of the GNU General Public License as published by
   9: the Free Software Foundation; either version 2, or (at your option)
  10: any later version.
  11: 
  12: GNU Classpath is distributed in the hope that it will be useful, but
  13: WITHOUT ANY WARRANTY; without even the implied warranty of
  14: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15: General Public License for more details.
  16: 
  17: You should have received a copy of the GNU General Public License
  18: along with GNU Classpath; see the file COPYING.  If not, write to the
  19: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  20: 02110-1301 USA.
  21: 
  22: Linking this library statically or dynamically with other modules is
  23: making a combined work based on this library.  Thus, the terms and
  24: conditions of the GNU General Public License cover the whole
  25: combination.
  26: 
  27: As a special exception, the copyright holders of this library give you
  28: permission to link this library with independent modules to produce an
  29: executable, regardless of the license terms of these independent
  30: modules, and to copy and distribute the resulting executable under
  31: terms of your choice, provided that you also meet, for each linked
  32: independent module, the terms and conditions of the license of that
  33: module.  An independent module is a module which is not derived from
  34: or based on this library.  If you modify this library, you may extend
  35: this exception to your version of the library, but you are not
  36: obligated to do so.  If you do not wish to do so, delete this
  37: exception statement from your version. */
  38: 
  39: package java.lang;
  40: 
  41: import gnu.classpath.VMStackWalker;
  42: import gnu.java.util.WeakIdentityHashMap;
  43: 
  44: import java.lang.management.ManagementFactory;
  45: import java.lang.management.ThreadInfo;
  46: import java.lang.management.ThreadMXBean;
  47: 
  48: import java.security.Permission;
  49: 
  50: import java.util.HashMap;
  51: import java.util.Map;
  52: 
  53: /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
  54:  * "The Java Language Specification", ISBN 0-201-63451-1
  55:  * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
  56:  * Status:  Believed complete to version 1.4, with caveats. We do not
  57:  *          implement the deprecated (and dangerous) stop, suspend, and resume
  58:  *          methods. Security implementation is not complete.
  59:  */
  60: 
  61: /**
  62:  * Thread represents a single thread of execution in the VM. When an
  63:  * application VM starts up, it creates a non-daemon Thread which calls the
  64:  * main() method of a particular class.  There may be other Threads running,
  65:  * such as the garbage collection thread.
  66:  *
  67:  * <p>Threads have names to identify them.  These names are not necessarily
  68:  * unique. Every Thread has a priority, as well, which tells the VM which
  69:  * Threads should get more running time. New threads inherit the priority
  70:  * and daemon status of the parent thread, by default.
  71:  *
  72:  * <p>There are two methods of creating a Thread: you may subclass Thread and
  73:  * implement the <code>run()</code> method, at which point you may start the
  74:  * Thread by calling its <code>start()</code> method, or you may implement
  75:  * <code>Runnable</code> in the class you want to use and then call new
  76:  * <code>Thread(your_obj).start()</code>.
  77:  *
  78:  * <p>The virtual machine runs until all non-daemon threads have died (either
  79:  * by returning from the run() method as invoked by start(), or by throwing
  80:  * an uncaught exception); or until <code>System.exit</code> is called with
  81:  * adequate permissions.
  82:  *
  83:  * <p>It is unclear at what point a Thread should be added to a ThreadGroup,
  84:  * and at what point it should be removed. Should it be inserted when it
  85:  * starts, or when it is created?  Should it be removed when it is suspended
  86:  * or interrupted?  The only thing that is clear is that the Thread should be
  87:  * removed when it is stopped.
  88:  *
  89:  * @author Tom Tromey
  90:  * @author John Keiser
  91:  * @author Eric Blake (ebb9@email.byu.edu)
  92:  * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  93:  * @see Runnable
  94:  * @see Runtime#exit(int)
  95:  * @see #run()
  96:  * @see #start()
  97:  * @see ThreadLocal
  98:  * @since 1.0
  99:  * @status updated to 1.4
 100:  */
 101: public class Thread implements Runnable
 102: {
 103:   /** The minimum priority for a Thread. */
 104:   public static final int MIN_PRIORITY = 1;
 105: 
 106:   /** The priority a Thread gets by default. */
 107:   public static final int NORM_PRIORITY = 5;
 108: 
 109:   /** The maximum priority for a Thread. */
 110:   public static final int MAX_PRIORITY = 10;
 111: 
 112:   /** The underlying VM thread, only set when the thread is actually running.
 113:    */
 114:   volatile VMThread vmThread;
 115: 
 116:   /**
 117:    * The group this thread belongs to. This is set to null by
 118:    * ThreadGroup.removeThread when the thread dies.
 119:    */
 120:   volatile ThreadGroup group;
 121: 
 122:   /** The object to run(), null if this is the target. */
 123:   final Runnable runnable;
 124: 
 125:   /** The thread name, non-null. */
 126:   volatile String name;
 127: 
 128:   /** Whether the thread is a daemon. */
 129:   volatile boolean daemon;
 130: 
 131:   /** The thread priority, 1 to 10. */
 132:   volatile int priority;
 133: 
 134:   /** Native thread stack size. 0 = use default */
 135:   private long stacksize;
 136: 
 137:   /** Was the thread stopped before it was started? */
 138:   Throwable stillborn;
 139: 
 140:   /** The context classloader for this Thread. */
 141:   private ClassLoader contextClassLoader;
 142:   private boolean contextClassLoaderIsSystemClassLoader;
 143: 
 144:   /** This thread's ID.  */
 145:   private final long threadId;
 146:   
 147:   /** The park blocker.  See LockSupport.  */
 148:   Object parkBlocker;
 149: 
 150:   /** The next thread number to use. */
 151:   private static int numAnonymousThreadsCreated;
 152:   
 153:   /** Used to generate the next thread ID to use.  */
 154:   private static long totalThreadsCreated;
 155: 
 156:   /** The default exception handler.  */
 157:   private static UncaughtExceptionHandler defaultHandler;
 158: 
 159:   /** Thread local storage. Package accessible for use by
 160:     * InheritableThreadLocal.
 161:     */
 162:   WeakIdentityHashMap locals;
 163: 
 164:   /** The uncaught exception handler.  */
 165:   UncaughtExceptionHandler exceptionHandler;
 166: 
 167:   /**
 168:    * Allocates a new <code>Thread</code> object. This constructor has
 169:    * the same effect as <code>Thread(null, null,</code>
 170:    * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
 171:    * a newly generated name. Automatically generated names are of the
 172:    * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
 173:    * <p>
 174:    * Threads created this way must have overridden their
 175:    * <code>run()</code> method to actually do anything.  An example
 176:    * illustrating this method being used follows:
 177:    * <p><blockquote><pre>
 178:    *     import java.lang.*;
 179:    *
 180:    *     class plain01 implements Runnable {
 181:    *         String name;
 182:    *         plain01() {
 183:    *             name = null;
 184:    *         }
 185:    *         plain01(String s) {
 186:    *             name = s;
 187:    *         }
 188:    *         public void run() {
 189:    *             if (name == null)
 190:    *                 System.out.println("A new thread created");
 191:    *             else
 192:    *                 System.out.println("A new thread with name " + name +
 193:    *                                    " created");
 194:    *         }
 195:    *     }
 196:    *     class threadtest01 {
 197:    *         public static void main(String args[] ) {
 198:    *             int failed = 0 ;
 199:    *
 200:    *             <b>Thread t1 = new Thread();</b>
 201:    *             if (t1 != null)
 202:    *                 System.out.println("new Thread() succeed");
 203:    *             else {
 204:    *                 System.out.println("new Thread() failed");
 205:    *                 failed++;
 206:    *             }
 207:    *         }
 208:    *     }
 209:    * </pre></blockquote>
 210:    *
 211:    * @see     java.lang.Thread#Thread(java.lang.ThreadGroup,
 212:    *          java.lang.Runnable, java.lang.String)
 213:    */
 214:   public Thread()
 215:   {
 216:     this(null, (Runnable) null);
 217:   }
 218: 
 219:   /**
 220:    * Allocates a new <code>Thread</code> object. This constructor has
 221:    * the same effect as <code>Thread(null, target,</code>
 222:    * <i>gname</i><code>)</code>, where <i>gname</i> is
 223:    * a newly generated name. Automatically generated names are of the
 224:    * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
 225:    *
 226:    * @param target the object whose <code>run</code> method is called.
 227:    * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
 228:    *                              java.lang.Runnable, java.lang.String)
 229:    */
 230:   public Thread(Runnable target)
 231:   {
 232:     this(null, target);
 233:   }
 234: 
 235:   /**
 236:    * Allocates a new <code>Thread</code> object. This constructor has
 237:    * the same effect as <code>Thread(null, null, name)</code>.
 238:    *
 239:    * @param   name   the name of the new thread.
 240:    * @see     java.lang.Thread#Thread(java.lang.ThreadGroup,
 241:    *          java.lang.Runnable, java.lang.String)
 242:    */
 243:   public Thread(String name)
 244:   {
 245:     this(null, null, name, 0);
 246:   }
 247: 
 248:   /**
 249:    * Allocates a new <code>Thread</code> object. This constructor has
 250:    * the same effect as <code>Thread(group, target,</code>
 251:    * <i>gname</i><code>)</code>, where <i>gname</i> is
 252:    * a newly generated name. Automatically generated names are of the
 253:    * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
 254:    *
 255:    * @param group the group to put the Thread into
 256:    * @param target the Runnable object to execute
 257:    * @throws SecurityException if this thread cannot access <code>group</code>
 258:    * @throws IllegalThreadStateException if group is destroyed
 259:    * @see #Thread(ThreadGroup, Runnable, String)
 260:    */
 261:   public Thread(ThreadGroup group, Runnable target)
 262:   {
 263:     this(group, target, createAnonymousThreadName(), 0);
 264:   }
 265: 
 266:   /**
 267:    * Allocates a new <code>Thread</code> object. This constructor has
 268:    * the same effect as <code>Thread(group, null, name)</code>
 269:    *
 270:    * @param group the group to put the Thread into
 271:    * @param name the name for the Thread
 272:    * @throws NullPointerException if name is null
 273:    * @throws SecurityException if this thread cannot access <code>group</code>
 274:    * @throws IllegalThreadStateException if group is destroyed
 275:    * @see #Thread(ThreadGroup, Runnable, String)
 276:    */
 277:   public Thread(ThreadGroup group, String name)
 278:   {
 279:     this(group, null, name, 0);
 280:   }
 281: 
 282:   /**
 283:    * Allocates a new <code>Thread</code> object. This constructor has
 284:    * the same effect as <code>Thread(null, target, name)</code>.
 285:    *
 286:    * @param target the Runnable object to execute
 287:    * @param name the name for the Thread
 288:    * @throws NullPointerException if name is null
 289:    * @see #Thread(ThreadGroup, Runnable, String)
 290:    */
 291:   public Thread(Runnable target, String name)
 292:   {
 293:     this(null, target, name, 0);
 294:   }
 295: 
 296:   /**
 297:    * Allocate a new Thread object, with the specified ThreadGroup and name, and
 298:    * using the specified Runnable object's <code>run()</code> method to
 299:    * execute.  If the Runnable object is null, <code>this</code> (which is
 300:    * a Runnable) is used instead.
 301:    *
 302:    * <p>If the ThreadGroup is null, the security manager is checked. If a
 303:    * manager exists and returns a non-null object for
 304:    * <code>getThreadGroup</code>, that group is used; otherwise the group
 305:    * of the creating thread is used. Note that the security manager calls
 306:    * <code>checkAccess</code> if the ThreadGroup is not null.
 307:    *
 308:    * <p>The new Thread will inherit its creator's priority and daemon status.
 309:    * These can be changed with <code>setPriority</code> and
 310:    * <code>setDaemon</code>.
 311:    *
 312:    * @param group the group to put the Thread into
 313:    * @param target the Runnable object to execute
 314:    * @param name the name for the Thread
 315:    * @throws NullPointerException if name is null
 316:    * @throws SecurityException if this thread cannot access <code>group</code>
 317:    * @throws IllegalThreadStateException if group is destroyed
 318:    * @see Runnable#run()
 319:    * @see #run()
 320:    * @see #setDaemon(boolean)
 321:    * @see #setPriority(int)
 322:    * @see SecurityManager#checkAccess(ThreadGroup)
 323:    * @see ThreadGroup#checkAccess()
 324:    */
 325:   public Thread(ThreadGroup group, Runnable target, String name)
 326:   {
 327:     this(group, target, name, 0);
 328:   }
 329: 
 330:   /**
 331:    * Allocate a new Thread object, as if by
 332:    * <code>Thread(group, null, name)</code>, and give it the specified stack
 333:    * size, in bytes. The stack size is <b>highly platform independent</b>,
 334:    * and the virtual machine is free to round up or down, or ignore it
 335:    * completely.  A higher value might let you go longer before a
 336:    * <code>StackOverflowError</code>, while a lower value might let you go
 337:    * longer before an <code>OutOfMemoryError</code>.  Or, it may do absolutely
 338:    * nothing! So be careful, and expect to need to tune this value if your
 339:    * virtual machine even supports it.
 340:    *
 341:    * @param group the group to put the Thread into
 342:    * @param target the Runnable object to execute
 343:    * @param name the name for the Thread
 344:    * @param size the stack size, in bytes; 0 to be ignored
 345:    * @throws NullPointerException if name is null
 346:    * @throws SecurityException if this thread cannot access <code>group</code>
 347:    * @throws IllegalThreadStateException if group is destroyed
 348:    * @since 1.4
 349:    */
 350:   public Thread(ThreadGroup group, Runnable target, String name, long size)
 351:   {
 352:     // Bypass System.getSecurityManager, for bootstrap efficiency.
 353:     SecurityManager sm = SecurityManager.current;
 354:     Thread current = currentThread();
 355:     if (group == null)
 356:       {
 357:     if (sm != null)
 358:       group = sm.getThreadGroup();
 359:     if (group == null)
 360:       group = current.group;
 361:       }
 362:     if (sm != null)
 363:       sm.checkAccess(group);
 364: 
 365:     this.group = group;
 366:     // Use toString hack to detect null.
 367:     this.name = name.toString();
 368:     this.runnable = target;
 369:     this.stacksize = size;
 370:     
 371:     synchronized (Thread.class)
 372:       {
 373:         this.threadId = ++totalThreadsCreated;
 374:       }
 375: 
 376:     priority = current.priority;
 377:     daemon = current.daemon;
 378:     contextClassLoader = current.contextClassLoader;
 379:     contextClassLoaderIsSystemClassLoader =
 380:         current.contextClassLoaderIsSystemClassLoader;
 381: 
 382:     group.addThread(this);
 383:     InheritableThreadLocal.newChildThread(this);
 384:   }
 385: 
 386:   /**
 387:    * Used by the VM to create thread objects for threads started outside
 388:    * of Java. Note: caller is responsible for adding the thread to
 389:    * a group and InheritableThreadLocal.
 390:    * Note: This constructor should not call any methods that could result
 391:    * in a call to Thread.currentThread(), because that makes life harder
 392:    * for the VM.
 393:    *
 394:    * @param vmThread the native thread
 395:    * @param name the thread name or null to use the default naming scheme
 396:    * @param priority current priority
 397:    * @param daemon is the thread a background thread?
 398:    */
 399:   Thread(VMThread vmThread, String name, int priority, boolean daemon)
 400:   {
 401:     this.vmThread = vmThread;
 402:     this.runnable = null;
 403:     if (name == null)
 404:       name = createAnonymousThreadName();
 405:     this.name = name;
 406:     this.priority = priority;
 407:     this.daemon = daemon;
 408:     // By default the context class loader is the system class loader,
 409:     // we set a flag to signal this because we don't want to call
 410:     // ClassLoader.getSystemClassLoader() at this point, because on
 411:     // VMs that lazily create the system class loader that might result
 412:     // in running user code (when a custom system class loader is specified)
 413:     // and that user code could call Thread.currentThread().
 414:     // ClassLoader.getSystemClassLoader() can also return null, if the system
 415:     // is currently in the process of constructing the system class loader
 416:     // (and, as above, the constructiong sequence calls Thread.currenThread()).
 417:     contextClassLoaderIsSystemClassLoader = true;
 418:     synchronized (Thread.class)
 419:     {
 420:       this.threadId = ++totalThreadsCreated;
 421:     }
 422:   }
 423:   
 424:   /**
 425:    * Generate a name for an anonymous thread.
 426:    */
 427:   private static synchronized String createAnonymousThreadName()
 428:   {
 429:     return "Thread-" + ++numAnonymousThreadsCreated;
 430:   }
 431: 
 432:   /**
 433:    * Get the number of active threads in the current Thread's ThreadGroup.
 434:    * This implementation calls
 435:    * <code>currentThread().getThreadGroup().activeCount()</code>.
 436:    *
 437:    * @return the number of active threads in the current ThreadGroup
 438:    * @see ThreadGroup#activeCount()
 439:    */
 440:   public static int activeCount()
 441:   {
 442:     return currentThread().group.activeCount();
 443:   }
 444: 
 445:   /**
 446:    * Check whether the current Thread is allowed to modify this Thread. This
 447:    * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
 448:    *
 449:    * @throws SecurityException if the current Thread cannot modify this Thread
 450:    * @see SecurityManager#checkAccess(Thread)
 451:    */
 452:   public final void checkAccess()
 453:   {
 454:     // Bypass System.getSecurityManager, for bootstrap efficiency.
 455:     SecurityManager sm = SecurityManager.current;
 456:     if (sm != null)
 457:       sm.checkAccess(this);
 458:   }
 459: 
 460:   /**
 461:    * Count the number of stack frames in this Thread.  The Thread in question
 462:    * must be suspended when this occurs.
 463:    *
 464:    * @return the number of stack frames in this Thread
 465:    * @throws IllegalThreadStateException if this Thread is not suspended
 466:    * @deprecated pointless, since suspend is deprecated
 467:    */
 468:   public int countStackFrames()
 469:   {
 470:     VMThread t = vmThread;
 471:     if (t == null || group == null)
 472:       throw new IllegalThreadStateException();
 473: 
 474:     return t.countStackFrames();
 475:   }
 476: 
 477:   /**
 478:    * Get the currently executing Thread. In the situation that the
 479:    * currently running thread was created by native code and doesn't
 480:    * have an associated Thread object yet, a new Thread object is
 481:    * constructed and associated with the native thread.
 482:    *
 483:    * @return the currently executing Thread
 484:    */
 485:   public static Thread currentThread()
 486:   {
 487:     return VMThread.currentThread();
 488:   }
 489: 
 490:   /**
 491:    * Originally intended to destroy this thread, this method was never
 492:    * implemented by Sun, and is hence a no-op.
 493:    *
 494:    * @deprecated This method was originally intended to simply destroy
 495:    *             the thread without performing any form of cleanup operation.
 496:    *             However, it was never implemented.  It is now deprecated
 497:    *             for the same reason as <code>suspend()</code>,
 498:    *             <code>stop()</code> and <code>resume()</code>; namely,
 499:    *             it is prone to deadlocks.  If a thread is destroyed while
 500:    *             it still maintains a lock on a resource, then this resource
 501:    *             will remain locked and any attempts by other threads to
 502:    *             access the resource will result in a deadlock.  Thus, even
 503:    *             an implemented version of this method would be still be
 504:    *             deprecated, due to its unsafe nature.
 505:    * @throws NoSuchMethodError as this method was never implemented.
 506:    */
 507:   public void destroy()
 508:   {
 509:     throw new NoSuchMethodError();
 510:   }
 511:   
 512:   /**
 513:    * Print a stack trace of the current thread to stderr using the same
 514:    * format as Throwable's printStackTrace() method.
 515:    *
 516:    * @see Throwable#printStackTrace()
 517:    */
 518:   public static void dumpStack()
 519:   {
 520:     new Throwable().printStackTrace();
 521:   }
 522: 
 523:   /**
 524:    * Copy every active thread in the current Thread's ThreadGroup into the
 525:    * array. Extra threads are silently ignored. This implementation calls
 526:    * <code>getThreadGroup().enumerate(array)</code>, which may have a
 527:    * security check, <code>checkAccess(group)</code>.
 528:    *
 529:    * @param array the array to place the Threads into
 530:    * @return the number of Threads placed into the array
 531:    * @throws NullPointerException if array is null
 532:    * @throws SecurityException if you cannot access the ThreadGroup
 533:    * @see ThreadGroup#enumerate(Thread[])
 534:    * @see #activeCount()
 535:    * @see SecurityManager#checkAccess(ThreadGroup)
 536:    */
 537:   public static int enumerate(Thread[] array)
 538:   {
 539:     return currentThread().group.enumerate(array);
 540:   }
 541:   
 542:   /**
 543:    * Get this Thread's name.
 544:    *
 545:    * @return this Thread's name
 546:    */
 547:   public final String getName()
 548:   {
 549:     VMThread t = vmThread;
 550:     return t == null ? name : t.getName();
 551:   }
 552: 
 553:   /**
 554:    * Get this Thread's priority.
 555:    *
 556:    * @return the Thread's priority
 557:    */
 558:   public final synchronized int getPriority()
 559:   {
 560:     VMThread t = vmThread;
 561:     return t == null ? priority : t.getPriority();
 562:   }
 563: 
 564:   /**
 565:    * Get the ThreadGroup this Thread belongs to. If the thread has died, this
 566:    * returns null.
 567:    *
 568:    * @return this Thread's ThreadGroup
 569:    */
 570:   public final ThreadGroup getThreadGroup()
 571:   {
 572:     return group;
 573:   }
 574: 
 575:   /**
 576:    * Checks whether the current thread holds the monitor on a given object.
 577:    * This allows you to do <code>assert Thread.holdsLock(obj)</code>.
 578:    *
 579:    * @param obj the object to test lock ownership on.
 580:    * @return true if the current thread is currently synchronized on obj
 581:    * @throws NullPointerException if obj is null
 582:    * @since 1.4
 583:    */
 584:   public static boolean holdsLock(Object obj)
 585:   {
 586:     return VMThread.holdsLock(obj);
 587:   }
 588: 
 589:   /**
 590:    * Interrupt this Thread. First, there is a security check,
 591:    * <code>checkAccess</code>. Then, depending on the current state of the
 592:    * thread, various actions take place:
 593:    *
 594:    * <p>If the thread is waiting because of {@link #wait()},
 595:    * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
 596:    * will be cleared, and an InterruptedException will be thrown. Notice that
 597:    * this case is only possible if an external thread called interrupt().
 598:    *
 599:    * <p>If the thread is blocked in an interruptible I/O operation, in
 600:    * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
 601:    * status</i> will be set, and ClosedByInterruptException will be thrown.
 602:    *
 603:    * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
 604:    * <i>interrupt status</i> will be set, and the selection will return, with
 605:    * a possible non-zero value, as though by the wakeup() method.
 606:    *
 607:    * <p>Otherwise, the interrupt status will be set.
 608:    *
 609:    * @throws SecurityException if you cannot modify this Thread
 610:    */
 611:   public synchronized void interrupt()
 612:   {
 613:     checkAccess();
 614:     VMThread t = vmThread;
 615:     if (t != null)
 616:       t.interrupt();
 617:   }
 618: 
 619:   /**
 620:    * Determine whether the current Thread has been interrupted, and clear
 621:    * the <i>interrupted status</i> in the process.
 622:    *
 623:    * @return whether the current Thread has been interrupted
 624:    * @see #isInterrupted()
 625:    */
 626:   public static boolean interrupted()
 627:   {
 628:     return VMThread.interrupted();
 629:   }
 630: 
 631:   /**
 632:    * Determine whether the given Thread has been interrupted, but leave
 633:    * the <i>interrupted status</i> alone in the process.
 634:    *
 635:    * @return whether the Thread has been interrupted
 636:    * @see #interrupted()
 637:    */
 638:   public boolean isInterrupted()
 639:   {
 640:     VMThread t = vmThread;
 641:     return t != null && t.isInterrupted();
 642:   }
 643: 
 644:   /**
 645:    * Determine whether this Thread is alive. A thread which is alive has
 646:    * started and not yet died.
 647:    *
 648:    * @return whether this Thread is alive
 649:    */
 650:   public final boolean isAlive()
 651:   {
 652:     return vmThread != null && group != null;
 653:   }
 654: 
 655:   /**
 656:    * Tell whether this is a daemon Thread or not.
 657:    *
 658:    * @return whether this is a daemon Thread or not
 659:    * @see #setDaemon(boolean)
 660:    */
 661:   public final boolean isDaemon()
 662:   {
 663:     VMThread t = vmThread;
 664:     return t == null ? daemon : t.isDaemon();
 665:   }
 666: 
 667:   /**
 668:    * Wait forever for the Thread in question to die.
 669:    *
 670:    * @throws InterruptedException if the Thread is interrupted; it's
 671:    *         <i>interrupted status</i> will be cleared
 672:    */
 673:   public final void join() throws InterruptedException
 674:   {
 675:     join(0, 0);
 676:   }
 677: 
 678:   /**
 679:    * Wait the specified amount of time for the Thread in question to die.
 680:    *
 681:    * @param ms the number of milliseconds to wait, or 0 for forever
 682:    * @throws InterruptedException if the Thread is interrupted; it's
 683:    *         <i>interrupted status</i> will be cleared
 684:    */
 685:   public final void join(long ms) throws InterruptedException
 686:   {
 687:     join(ms, 0);
 688:   }
 689: 
 690:   /**
 691:    * Wait the specified amount of time for the Thread in question to die.
 692:    *
 693:    * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
 694:    * not offer that fine a grain of timing resolution. Besides, there is
 695:    * no guarantee that this thread can start up immediately when time expires,
 696:    * because some other thread may be active.  So don't expect real-time
 697:    * performance.
 698:    *
 699:    * @param ms the number of milliseconds to wait, or 0 for forever
 700:    * @param ns the number of extra nanoseconds to sleep (0-999999)
 701:    * @throws InterruptedException if the Thread is interrupted; it's
 702:    *         <i>interrupted status</i> will be cleared
 703:    * @throws IllegalArgumentException if ns is invalid
 704:    */
 705:   public final void join(long ms, int ns) throws InterruptedException
 706:   {
 707:     if (ms < 0 || ns < 0 || ns > 999999)
 708:       throw new IllegalArgumentException();
 709: 
 710:     VMThread t = vmThread;
 711:     if (t != null)
 712:       t.join(ms, ns);
 713:   }
 714: 
 715:   /**
 716:    * Resume this Thread.  If the thread is not suspended, this method does
 717:    * nothing. To mirror suspend(), there may be a security check:
 718:    * <code>checkAccess</code>.
 719:    *
 720:    * @throws SecurityException if you cannot resume the Thread
 721:    * @see #checkAccess()
 722:    * @see #suspend()
 723:    * @deprecated pointless, since suspend is deprecated
 724:    */
 725:   public final synchronized void resume()
 726:   {
 727:     checkAccess();
 728:     VMThread t = vmThread;
 729:     if (t != null)
 730:       t.resume();
 731:   }
 732:   
 733:   /**
 734:    * The method of Thread that will be run if there is no Runnable object
 735:    * associated with the Thread. Thread's implementation does nothing at all.
 736:    *
 737:    * @see #start()
 738:    * @see #Thread(ThreadGroup, Runnable, String)
 739:    */
 740:   public void run()
 741:   {
 742:     if (runnable != null)
 743:       runnable.run();
 744:   }
 745: 
 746:   /**
 747:    * Set the daemon status of this Thread.  If this is a daemon Thread, then
 748:    * the VM may exit even if it is still running.  This may only be called
 749:    * before the Thread starts running. There may be a security check,
 750:    * <code>checkAccess</code>.
 751:    *
 752:    * @param daemon whether this should be a daemon thread or not
 753:    * @throws SecurityException if you cannot modify this Thread
 754:    * @throws IllegalThreadStateException if the Thread is active
 755:    * @see #isDaemon()
 756:    * @see #checkAccess()
 757:    */
 758:   public final synchronized void setDaemon(boolean daemon)
 759:   {
 760:     if (vmThread != null)
 761:       throw new IllegalThreadStateException();
 762:     checkAccess();
 763:     this.daemon = daemon;
 764:   }
 765: 
 766:   /**
 767:    * Returns the context classloader of this Thread. The context
 768:    * classloader can be used by code that want to load classes depending
 769:    * on the current thread. Normally classes are loaded depending on
 770:    * the classloader of the current class. There may be a security check
 771:    * for <code>RuntimePermission("getClassLoader")</code> if the caller's
 772:    * class loader is not null or an ancestor of this thread's context class
 773:    * loader.
 774:    *
 775:    * @return the context class loader
 776:    * @throws SecurityException when permission is denied
 777:    * @see #setContextClassLoader(ClassLoader)
 778:    * @since 1.2
 779:    */
 780:   public synchronized ClassLoader getContextClassLoader()
 781:   {
 782:     ClassLoader loader = contextClassLoaderIsSystemClassLoader ?
 783:         ClassLoader.getSystemClassLoader() : contextClassLoader;
 784:     // Check if we may get the classloader
 785:     SecurityManager sm = SecurityManager.current;
 786:     if (loader != null && sm != null)
 787:       {
 788:         // Get the calling classloader
 789:     ClassLoader cl = VMStackWalker.getCallingClassLoader();
 790:         if (cl != null && !cl.isAncestorOf(loader))
 791:           sm.checkPermission(new RuntimePermission("getClassLoader"));
 792:       }
 793:     return loader;
 794:   }
 795: 
 796:   /**
 797:    * Sets the context classloader for this Thread. When not explicitly set,
 798:    * the context classloader for a thread is the same as the context
 799:    * classloader of the thread that created this thread. The first thread has
 800:    * as context classloader the system classloader. There may be a security
 801:    * check for <code>RuntimePermission("setContextClassLoader")</code>.
 802:    *
 803:    * @param classloader the new context class loader
 804:    * @throws SecurityException when permission is denied
 805:    * @see #getContextClassLoader()
 806:    * @since 1.2
 807:    */
 808:   public synchronized void setContextClassLoader(ClassLoader classloader)
 809:   {
 810:     SecurityManager sm = SecurityManager.current;
 811:     if (sm != null)
 812:       sm.checkPermission(new RuntimePermission("setContextClassLoader"));
 813:     this.contextClassLoader = classloader;
 814:     contextClassLoaderIsSystemClassLoader = false;
 815:   }
 816: 
 817:   /**
 818:    * Set this Thread's name.  There may be a security check,
 819:    * <code>checkAccess</code>.
 820:    *
 821:    * @param name the new name for this Thread
 822:    * @throws NullPointerException if name is null
 823:    * @throws SecurityException if you cannot modify this Thread
 824:    */
 825:   public final synchronized void setName(String name)
 826:   {
 827:     checkAccess();
 828:     // The Class Libraries book says ``threadName cannot be null''.  I
 829:     // take this to mean NullPointerException.
 830:     if (name == null)
 831:       throw new NullPointerException();
 832:     VMThread t = vmThread;
 833:     if (t != null)
 834:       t.setName(name);
 835:     else
 836:       this.name = name;
 837:   }
 838: 
 839:   /**
 840:    * Yield to another thread. The Thread will not lose any locks it holds
 841:    * during this time. There are no guarantees which thread will be
 842:    * next to run, and it could even be this one, but most VMs will choose
 843:    * the highest priority thread that has been waiting longest.
 844:    */
 845:   public static void yield()
 846:   {
 847:     VMThread.yield();
 848:   }
 849: 
 850:   /**
 851:    * Suspend the current Thread's execution for the specified amount of
 852:    * time. The Thread will not lose any locks it has during this time. There
 853:    * are no guarantees which thread will be next to run, but most VMs will
 854:    * choose the highest priority thread that has been waiting longest.
 855:    *
 856:    * @param ms the number of milliseconds to sleep, or 0 for forever
 857:    * @throws InterruptedException if the Thread is (or was) interrupted;
 858:    *         it's <i>interrupted status</i> will be cleared
 859:    * @throws IllegalArgumentException if ms is negative
 860:    * @see #interrupt()
 861:    * @see #notify()
 862:    * @see #wait(long)
 863:    */
 864:   public static void sleep(long ms) throws InterruptedException
 865:   {
 866:     sleep(ms, 0);
 867:   }
 868: 
 869:   /**
 870:    * Suspend the current Thread's execution for the specified amount of
 871:    * time. The Thread will not lose any locks it has during this time. There
 872:    * are no guarantees which thread will be next to run, but most VMs will
 873:    * choose the highest priority thread that has been waiting longest.
 874:    * <p>
 875:    * Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs
 876:    * do not offer that fine a grain of timing resolution. When ms is
 877:    * zero and ns is non-zero the Thread will sleep for at least one
 878:    * milli second. There is no guarantee that this thread can start up
 879:    * immediately when time expires, because some other thread may be
 880:    * active.  So don't expect real-time performance.
 881:    *
 882:    * @param ms the number of milliseconds to sleep, or 0 for forever
 883:    * @param ns the number of extra nanoseconds to sleep (0-999999)
 884:    * @throws InterruptedException if the Thread is (or was) interrupted;
 885:    *         it's <i>interrupted status</i> will be cleared
 886:    * @throws IllegalArgumentException if ms or ns is negative
 887:    *         or ns is larger than 999999.
 888:    * @see #interrupt()
 889:    * @see #notify()
 890:    * @see #wait(long, int)
 891:    */
 892:   public static void sleep(long ms, int ns) throws InterruptedException
 893:   {
 894:     // Check parameters
 895:     if (ms < 0 )
 896:       throw new IllegalArgumentException("Negative milliseconds: " + ms);
 897: 
 898:     if (ns < 0 || ns > 999999)
 899:       throw new IllegalArgumentException("Nanoseconds ouf of range: " + ns);
 900: 
 901:     // Really sleep
 902:     VMThread.sleep(ms, ns);
 903:   }
 904: 
 905:   /**
 906:    * Start this Thread, calling the run() method of the Runnable this Thread
 907:    * was created with, or else the run() method of the Thread itself. This
 908:    * is the only way to start a new thread; calling run by yourself will just
 909:    * stay in the same thread. The virtual machine will remove the thread from
 910:    * its thread group when the run() method completes.
 911:    *
 912:    * @throws IllegalThreadStateException if the thread has already started
 913:    * @see #run()
 914:    */
 915:   public synchronized void start()
 916:   {
 917:     if (vmThread != null || group == null)
 918:       throw new IllegalThreadStateException();
 919: 
 920:     VMThread.create(this, stacksize);
 921:   }
 922:   
 923:   /**
 924:    * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
 925:    * error. If you stop a Thread that has not yet started, it will stop
 926:    * immediately when it is actually started.
 927:    *
 928:    * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
 929:    * leave data in bad states.  Hence, there is a security check:
 930:    * <code>checkAccess(this)</code>, plus another one if the current thread
 931:    * is not this: <code>RuntimePermission("stopThread")</code>. If you must
 932:    * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
 933:    * ThreadDeath is the only exception which does not print a stack trace when
 934:    * the thread dies.
 935:    *
 936:    * @throws SecurityException if you cannot stop the Thread
 937:    * @see #interrupt()
 938:    * @see #checkAccess()
 939:    * @see #start()
 940:    * @