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