1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 /* 18 * Copyright (C) 2008 The Android Open Source Project 19 * 20 * Licensed under the Apache License, Version 2.0 (the "License"); 21 * you may not use this file except in compliance with the License. 22 * You may obtain a copy of the License at 23 * 24 * http://www.apache.org/licenses/LICENSE-2.0 25 * 26 * Unless required by applicable law or agreed to in writing, software 27 * distributed under the License is distributed on an "AS IS" BASIS, 28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 29 * See the License for the specific language governing permissions and 30 * limitations under the License. 31 */ 32 33 package java.lang; 34 35 import dalvik.system.VMStack; 36 import java.util.ArrayList; 37 import java.util.HashMap; 38 import java.util.List; 39 import java.util.Map; 40 import libcore.util.EmptyArray; 41 42 /** 43 * A {@code Thread} is a concurrent unit of execution. It has its own call stack 44 * for methods being invoked, their arguments and local variables. Each application 45 * has at least one thread running when it is started, the main thread, in the main 46 * {@link ThreadGroup}. The runtime keeps its own threads in the system thread 47 * group. 48 * 49 * <p>There are two ways to execute code in a new thread. 50 * You can either subclass {@code Thread} and overriding its {@link #run()} method, 51 * or construct a new {@code Thread} and pass a {@link Runnable} to the constructor. 52 * In either case, the {@link #start()} method must be called to actually execute 53 * the new {@code Thread}. 54 * 55 * <p>Each {@code Thread} has an integer priority that affect how the thread is 56 * scheduled by the OS. A new thread inherits the priority of its parent. 57 * A thread's priority can be set using the {@link #setPriority(int)} method. 58 */ 59 public class Thread implements Runnable { 60 private static final int NANOS_PER_MILLI = 1000000; 61 62 /** Park states */ 63 private static class ParkState { 64 /** park state indicating unparked */ 65 private static final int UNPARKED = 1; 66 67 /** park state indicating preemptively unparked */ 68 private static final int PREEMPTIVELY_UNPARKED = 2; 69 70 /** park state indicating parked */ 71 private static final int PARKED = 3; 72 } 73 74 /** 75 * A representation of a thread's state. A given thread may only be in one 76 * state at a time. 77 */ 78 public enum State { 79 /** 80 * The thread has been created, but has never been started. 81 */ 82 NEW, 83 /** 84 * The thread may be run. 85 */ 86 RUNNABLE, 87 /** 88 * The thread is blocked and waiting for a lock. 89 */ 90 BLOCKED, 91 /** 92 * The thread is waiting. 93 */ 94 WAITING, 95 /** 96 * The thread is waiting for a specified amount of time. 97 */ 98 TIMED_WAITING, 99 /** 100 * The thread has been terminated. 101 */ 102 TERMINATED 103 } 104 105 /** 106 * The maximum priority value allowed for a thread. 107 * This corresponds to (but does not have the same value as) 108 * {@code android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY}. 109 */ 110 public static final int MAX_PRIORITY = 10; 111 112 /** 113 * The minimum priority value allowed for a thread. 114 * This corresponds to (but does not have the same value as) 115 * {@code android.os.Process.THREAD_PRIORITY_LOWEST}. 116 */ 117 public static final int MIN_PRIORITY = 1; 118 119 /** 120 * The normal (default) priority value assigned to the main thread. 121 * This corresponds to (but does not have the same value as) 122 * {@code android.os.Process.THREAD_PRIORITY_DEFAULT}. 123 124 */ 125 public static final int NORM_PRIORITY = 5; 126 127 /* Some of these are accessed directly by the VM; do not rename them. */ 128 private volatile long nativePeer; 129 volatile ThreadGroup group; 130 volatile boolean daemon; 131 volatile String name; 132 volatile int priority; 133 volatile long stackSize; 134 Runnable target; 135 private static int count = 0; 136 137 /** 138 * Holds the thread's ID. We simply count upwards, so 139 * each Thread has a unique ID. 140 */ 141 private long id; 142 143 /** 144 * Normal thread local values. 145 */ 146 ThreadLocal.Values localValues; 147 148 /** 149 * Inheritable thread local values. 150 */ 151 ThreadLocal.Values inheritableValues; 152 153 /** Callbacks to run on interruption. */ 154 private final List<Runnable> interruptActions = new ArrayList<Runnable>(); 155 156 /** 157 * Holds the class loader for this Thread, in case there is one. 158 */ 159 private ClassLoader contextClassLoader; 160 161 /** 162 * Holds the handler for uncaught exceptions in this Thread, 163 * in case there is one. 164 */ 165 private UncaughtExceptionHandler uncaughtHandler; 166 167 /** 168 * Holds the default handler for uncaught exceptions, in case there is one. 169 */ 170 private static UncaughtExceptionHandler defaultUncaughtHandler; 171 172 /** 173 * Reflects whether this Thread has already been started. A Thread 174 * can only be started once (no recycling). Also, we need it to deduce 175 * the proper Thread status. 176 */ 177 boolean hasBeenStarted = false; 178 179 /** the park state of the thread */ 180 private int parkState = ParkState.UNPARKED; 181 182 /** 183 * The synchronization object responsible for this thread's join/sleep/park operations. 184 */ 185 private final Object lock = new Object(); 186 187 /** Looked up reflectively and used by java.util.concurrent.locks.LockSupport. */ 188 private Object parkBlocker; 189 190 /** 191 * Constructs a new {@code Thread} with no {@code Runnable} object and a 192 * newly generated name. The new {@code Thread} will belong to the same 193 * {@code ThreadGroup} as the {@code Thread} calling this constructor. 194 * 195 * @see java.lang.ThreadGroup 196 * @see java.lang.Runnable 197 */ 198 public Thread() { 199 create(null, null, null, 0); 200 } 201 202 /** 203 * Constructs a new {@code Thread} with a {@code Runnable} object and a 204 * newly generated name. The new {@code Thread} will belong to the same 205 * {@code ThreadGroup} as the {@code Thread} calling this constructor. 206 * 207 * @param runnable 208 * a {@code Runnable} whose method <code>run</code> will be 209 * executed by the new {@code Thread} 210 * 211 * @see java.lang.ThreadGroup 212 * @see java.lang.Runnable 213 */ 214 public Thread(Runnable runnable) { 215 create(null, runnable, null, 0); 216 } 217 218 /** 219 * Constructs a new {@code Thread} with a {@code Runnable} object and name 220 * provided. The new {@code Thread} will belong to the same {@code 221 * ThreadGroup} as the {@code Thread} calling this constructor. 222 * 223 * @param runnable 224 * a {@code Runnable} whose method <code>run</code> will be 225 * executed by the new {@code Thread} 226 * @param threadName 227 * the name for the {@code Thread} being created 228 * 229 * @see java.lang.ThreadGroup 230 * @see java.lang.Runnable 231 */ 232 public Thread(Runnable runnable, String threadName) { 233 if (threadName == null) { 234 throw new NullPointerException("threadName == null"); 235 } 236 237 create(null, runnable, threadName, 0); 238 } 239 240 /** 241 * Constructs a new {@code Thread} with no {@code Runnable} object and the 242 * name provided. The new {@code Thread} will belong to the same {@code 243 * ThreadGroup} as the {@code Thread} calling this constructor. 244 * 245 * @param threadName 246 * the name for the {@code Thread} being created 247 * 248 * @see java.lang.ThreadGroup 249 * @see java.lang.Runnable 250 * 251 */ 252 public Thread(String threadName) { 253 if (threadName == null) { 254 throw new NullPointerException("threadName == null"); 255 } 256 257 create(null, null, threadName, 0); 258 } 259 260 /** 261 * Constructs a new {@code Thread} with a {@code Runnable} object and a 262 * newly generated name. The new {@code Thread} will belong to the {@code 263 * ThreadGroup} passed as parameter. 264 * 265 * @param group 266 * {@code ThreadGroup} to which the new {@code Thread} will 267 * belong 268 * @param runnable 269 * a {@code Runnable} whose method <code>run</code> will be 270 * executed by the new {@code Thread} 271 * @throws IllegalThreadStateException 272 * if <code>group.destroy()</code> has already been done 273 * @see java.lang.ThreadGroup 274 * @see java.lang.Runnable 275 */ 276 public Thread(ThreadGroup group, Runnable runnable) { 277 create(group, runnable, null, 0); 278 } 279 280 /** 281 * Constructs a new {@code Thread} with a {@code Runnable} object, the given 282 * name and belonging to the {@code ThreadGroup} passed as parameter. 283 * 284 * @param group 285 * ThreadGroup to which the new {@code Thread} will belong 286 * @param runnable 287 * a {@code Runnable} whose method <code>run</code> will be 288 * executed by the new {@code Thread} 289 * @param threadName 290 * the name for the {@code Thread} being created 291 * @throws IllegalThreadStateException 292 * if <code>group.destroy()</code> has already been done 293 * @see java.lang.ThreadGroup 294 * @see java.lang.Runnable 295 */ 296 public Thread(ThreadGroup group, Runnable runnable, String threadName) { 297 if (threadName == null) { 298 throw new NullPointerException("threadName == null"); 299 } 300 301 create(group, runnable, threadName, 0); 302 } 303 304 /** 305 * Constructs a new {@code Thread} with no {@code Runnable} object, the 306 * given name and belonging to the {@code ThreadGroup} passed as parameter. 307 * 308 * @param group 309 * {@code ThreadGroup} to which the new {@code Thread} will belong 310 * @param threadName 311 * the name for the {@code Thread} being created 312 * @throws IllegalThreadStateException 313 * if <code>group.destroy()</code> has already been done 314 * @see java.lang.ThreadGroup 315 * @see java.lang.Runnable 316 */ 317 public Thread(ThreadGroup group, String threadName) { 318 if (threadName == null) { 319 throw new NullPointerException("threadName == null"); 320 } 321 322 create(group, null, threadName, 0); 323 } 324 325 /** 326 * Constructs a new {@code Thread} with a {@code Runnable} object, the given 327 * name and belonging to the {@code ThreadGroup} passed as parameter. 328 * 329 * @param group 330 * {@code ThreadGroup} to which the new {@code Thread} will 331 * belong 332 * @param runnable 333 * a {@code Runnable} whose method <code>run</code> will be 334 * executed by the new {@code Thread} 335 * @param threadName 336 * the name for the {@code Thread} being created 337 * @param stackSize 338 * a stack size for the new {@code Thread}. This has a highly 339 * platform-dependent interpretation. It may even be ignored 340 * completely. 341 * @throws IllegalThreadStateException 342 * if <code>group.destroy()</code> has already been done 343 * @see java.lang.ThreadGroup 344 * @see java.lang.Runnable 345 */ 346 public Thread(ThreadGroup group, Runnable runnable, String threadName, long stackSize) { 347 if (threadName == null) { 348 throw new NullPointerException("threadName == null"); 349 } 350 create(group, runnable, threadName, stackSize); 351 } 352 353 /** 354 * Package-scope method invoked by Dalvik VM to create "internal" 355 * threads or attach threads created externally. 356 * 357 * Don't call Thread.currentThread(), since there may not be such 358 * a thing (e.g. for Main). 359 */ 360 Thread(ThreadGroup group, String name, int priority, boolean daemon) { 361 synchronized (Thread.class) { 362 id = ++Thread.count; 363 } 364 365 if (name == null) { 366 this.name = "Thread-" + id; 367 } else { 368 this.name = name; 369 } 370 371 if (group == null) { 372 throw new InternalError("group == null"); 373 } 374 375 this.group = group; 376 377 this.target = null; 378 this.stackSize = 0; 379 this.priority = priority; 380 this.daemon = daemon; 381 382 /* add ourselves to our ThreadGroup of choice */ 383 this.group.addThread(this); 384 } 385 386 /** 387 * Initializes a new, existing Thread object with a runnable object, 388 * the given name and belonging to the ThreadGroup passed as parameter. 389 * This is the method that the several public constructors delegate their 390 * work to. 391 * 392 * @param group ThreadGroup to which the new Thread will belong 393 * @param runnable a java.lang.Runnable whose method <code>run</code> will 394 * be executed by the new Thread 395 * @param threadName Name for the Thread being created 396 * @param stackSize Platform dependent stack size 397 * @throws IllegalThreadStateException if <code>group.destroy()</code> has 398 * already been done 399 * @see java.lang.ThreadGroup 400 * @see java.lang.Runnable 401 */ 402 private void create(ThreadGroup group, Runnable runnable, String threadName, long stackSize) { 403 Thread currentThread = Thread.currentThread(); 404 if (group == null) { 405 group = currentThread.getThreadGroup(); 406 } 407 408 if (group.isDestroyed()) { 409 throw new IllegalThreadStateException("Group already destroyed"); 410 } 411 412 this.group = group; 413 414 synchronized (Thread.class) { 415 id = ++Thread.count; 416 } 417 418 if (threadName == null) { 419 this.name = "Thread-" + id; 420 } else { 421 this.name = threadName; 422 } 423 424 this.target = runnable; 425 this.stackSize = stackSize; 426 427 this.priority = currentThread.getPriority(); 428 429 this.contextClassLoader = currentThread.contextClassLoader; 430 431 // Transfer over InheritableThreadLocals. 432 if (currentThread.inheritableValues != null) { 433 inheritableValues = new ThreadLocal.Values(currentThread.inheritableValues); 434 } 435 436 // add ourselves to our ThreadGroup of choice 437 this.group.addThread(this); 438 } 439 440 /** 441 * Returns the number of active {@code Thread}s in the running {@code 442 * Thread}'s group and its subgroups. 443 * 444 * @return the number of {@code Thread}s 445 */ 446 public static int activeCount() { 447 return currentThread().getThreadGroup().activeCount(); 448 } 449 450 /** 451 * Does nothing. 452 */ 453 public final void checkAccess() { 454 } 455 456 /** 457 * Returns the number of stack frames in this thread. 458 * 459 * @return Number of stack frames 460 * @deprecated The results of this call were never well defined. To make 461 * things worse, it would depend on whether the Thread was 462 * suspended or not, and suspend was deprecated too. 463 */ 464 @Deprecated 465 public int countStackFrames() { 466 return getStackTrace().length; 467 } 468 469 /** 470 * Returns the Thread of the caller, that is, the current Thread. 471 */ 472 public static native Thread currentThread(); 473 474 /** 475 * Throws {@code UnsupportedOperationException}. 476 * @deprecated Not implemented. 477 */ 478 @Deprecated 479 public void destroy() { 480 throw new UnsupportedOperationException(); 481 } 482 483 /** 484 * Prints to the standard error stream a text representation of the current 485 * stack for this Thread. 486 * 487 * @see Throwable#printStackTrace() 488 */ 489 public static void dumpStack() { 490 new Throwable("stack dump").printStackTrace(); 491 } 492 493 /** 494 * Copies an array with all Threads which are in the same ThreadGroup as the 495 * receiver - and subgroups - into the array <code>threads</code> passed as 496 * parameter. If the array passed as parameter is too small no exception is 497 * thrown - the extra elements are simply not copied. 498 * 499 * @param threads 500 * array into which the Threads will be copied 501 * @return How many Threads were copied over 502 */ 503 public static int enumerate(Thread[] threads) { 504 Thread thread = Thread.currentThread(); 505 return thread.getThreadGroup().enumerate(threads); 506 } 507 508 /** 509 * Returns a map of all the currently live threads to their stack traces. 510 */ 511 public static Map<Thread, StackTraceElement[]> getAllStackTraces() { 512 Map<Thread, StackTraceElement[]> map = new HashMap<Thread, StackTraceElement[]>(); 513 514 // Find out how many live threads we have. Allocate a bit more 515 // space than needed, in case new ones are just being created. 516 int count = ThreadGroup.systemThreadGroup.activeCount(); 517 Thread[] threads = new Thread[count + count / 2]; 518 519 // Enumerate the threads and collect the stacktraces. 520 count = ThreadGroup.systemThreadGroup.enumerate(threads); 521 for (int i = 0; i < count; i++) { 522 map.put(threads[i], threads[i].getStackTrace()); 523 } 524 525 return map; 526 } 527 528 /** 529 * Returns the context ClassLoader for this Thread. 530 * 531 * @return ClassLoader The context ClassLoader 532 * @see java.lang.ClassLoader 533 * @see #getContextClassLoader() 534 */ 535 public ClassLoader getContextClassLoader() { 536 return contextClassLoader; 537 } 538 539 /** 540 * Returns the default exception handler that's executed when uncaught 541 * exception terminates a thread. 542 * 543 * @return an {@link UncaughtExceptionHandler} or <code>null</code> if 544 * none exists. 545 */ 546 public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() { 547 return defaultUncaughtHandler; 548 } 549 550 /** 551 * Returns the thread's identifier. The ID is a positive <code>long</code> 552 * generated on thread creation, is unique to the thread, and doesn't change 553 * during the lifetime of the thread; the ID may be reused after the thread 554 * has been terminated. 555 * 556 * @return the thread's ID. 557 */ 558 public long getId() { 559 return id; 560 } 561 562 /** 563 * Returns the name of the Thread. 564 */ 565 public final String getName() { 566 return name; 567 } 568 569 /** 570 * Returns the priority of the Thread. 571 */ 572 public final int getPriority() { 573 return priority; 574 } 575 576 /** 577 * Returns an array of {@link StackTraceElement} representing the current thread's stack. 578 */ 579 public StackTraceElement[] getStackTrace() { 580 StackTraceElement ste[] = VMStack.getThreadStackTrace(this); 581 return ste != null ? ste : EmptyArray.STACK_TRACE_ELEMENT; 582 } 583 584 /** 585 * Returns the current state of the Thread. This method is useful for 586 * monitoring purposes. 587 * 588 * @return a {@link State} value. 589 */ 590 public State getState() { 591 return State.values()[nativeGetStatus(hasBeenStarted)]; 592 } 593 594 private native int nativeGetStatus(boolean hasBeenStarted); 595 596 /** 597 * Returns the ThreadGroup to which this Thread belongs. 598 * 599 * @return the Thread's ThreadGroup 600 */ 601 public final ThreadGroup getThreadGroup() { 602 // TODO This should actually be done at native termination. 603 if (getState() == Thread.State.TERMINATED) { 604 return null; 605 } else { 606 return group; 607 } 608 } 609 610 /** 611 * Returns the thread's uncaught exception handler. If not explicitly set, 612 * then the ThreadGroup's handler is returned. If the thread is terminated, 613 * then <code>null</code> is returned. 614 * 615 * @return an {@link UncaughtExceptionHandler} instance or {@code null}. 616 */ 617 public UncaughtExceptionHandler getUncaughtExceptionHandler() { 618 if (uncaughtHandler != null) { 619 return uncaughtHandler; 620 } else { 621 return group; // ThreadGroup is instance of UEH 622 } 623 } 624 625 /** 626 * Posts an interrupt request to this {@code Thread}. The behavior depends on 627 * the state of this {@code Thread}: 628 * <ul> 629 * <li> 630 * {@code Thread}s blocked in one of {@code Object}'s {@code wait()} methods 631 * or one of {@code Thread}'s {@code join()} or {@code sleep()} methods will 632 * be woken up, their interrupt status will be cleared, and they receive an 633 * {@link InterruptedException}. 634 * <li> 635 * {@code Thread}s blocked in an I/O operation of an 636 * {@link java.nio.channels.InterruptibleChannel} will have their interrupt 637 * status set and receive an 638 * {@link java.nio.channels.ClosedByInterruptException}. Also, the channel 639 * will be closed. 640 * <li> 641 * {@code Thread}s blocked in a {@link java.nio.channels.Selector} will have 642 * their interrupt status set and return immediately. They don't receive an 643 * exception in this case. 644 * <ul> 645 * 646 * @see Thread#interrupted 647 * @see Thread#isInterrupted 648 */ 649 public void interrupt() { 650 // Interrupt this thread before running actions so that other 651 // threads that observe the interrupt as a result of an action 652 // will see that this thread is in the interrupted state. 653 nativeInterrupt(); 654 655 synchronized (interruptActions) { 656 for (int i = interruptActions.size() - 1; i >= 0; i--) { 657 interruptActions.get(i).run(); 658 } 659 } 660 } 661 662 private native void nativeInterrupt(); 663 664 /** 665 * Returns a <code>boolean</code> indicating whether the current Thread ( 666 * <code>currentThread()</code>) has a pending interrupt request (<code> 667 * true</code>) or not (<code>false</code>). It also has the side-effect of 668 * clearing the flag. 669 * 670 * @return a <code>boolean</code> indicating the interrupt status 671 * @see Thread#currentThread 672 * @see Thread#interrupt 673 * @see Thread#isInterrupted 674 */ 675 public static native boolean interrupted(); 676 677 /** 678 * Returns <code>true</code> if the receiver has already been started and 679 * still runs code (hasn't died yet). Returns <code>false</code> either if 680 * the receiver hasn't been started yet or if it has already started and run 681 * to completion and died. 682 * 683 * @return a <code>boolean</code> indicating the liveness of the Thread 684 * @see Thread#start 685 */ 686 public final boolean isAlive() { 687 return (nativePeer != 0); 688 } 689 690 /** 691 * Tests whether this is a daemon thread. 692 * A daemon thread only runs as long as there are non-daemon threads running. 693 * When the last non-daemon thread ends, the runtime will exit. This is not 694 * normally relevant to applications with a UI. 695 */ 696 public final boolean isDaemon() { 697 return daemon; 698 } 699 700 /** 701 * Returns a <code>boolean</code> indicating whether the receiver has a 702 * pending interrupt request (<code>true</code>) or not ( 703 * <code>false</code>) 704 * 705 * @return a <code>boolean</code> indicating the interrupt status 706 * @see Thread#interrupt 707 * @see Thread#interrupted 708 */ 709 public native boolean isInterrupted(); 710 711 /** 712 * Blocks the current Thread (<code>Thread.currentThread()</code>) until 713 * the receiver finishes its execution and dies. 714 * 715 * @throws InterruptedException if the current thread has been interrupted. 716 * The interrupted status of the current thread will be cleared before the exception is 717 * thrown. 718 * @see Object#notifyAll 719 * @see java.lang.ThreadDeath 720 */ 721 public final void join() throws InterruptedException { 722 synchronized (lock) { 723 while (isAlive()) { 724 lock.wait(); 725 } 726 } 727 } 728 729 /** 730 * Blocks the current Thread (<code>Thread.currentThread()</code>) until 731 * the receiver finishes its execution and dies or the specified timeout 732 * expires, whatever happens first. 733 * 734 * <p>A timeout of zero means the calling thread should wait forever unless interrupted. 735 * 736 * @param millis The maximum time to wait (in milliseconds). 737 * @throws InterruptedException if the current thread has been interrupted. 738 * The interrupted status of the current thread will be cleared before the exception is 739 * thrown. 740 * @see Object#notifyAll 741 * @see java.lang.ThreadDeath 742 */ 743 public final void join(long millis) throws InterruptedException { 744 join(millis, 0); 745 } 746 747 /** 748 * Blocks the current Thread (<code>Thread.currentThread()</code>) until 749 * the receiver finishes its execution and dies or the specified timeout 750 * expires, whatever happens first. 751 * 752 * <p>A timeout of zero means the calling thread should wait forever unless interrupted. 753 * 754 * @param millis The maximum time to wait (in milliseconds). 755 * @param nanos Extra nanosecond precision 756 * @throws InterruptedException if the current thread has been interrupted. 757 * The interrupted status of the current thread will be cleared before the exception is 758 * thrown. 759 * @see Object#notifyAll 760 * @see java.lang.ThreadDeath 761 */ 762 public final void join(long millis, int nanos) throws InterruptedException { 763 if (millis < 0 || nanos < 0 || nanos >= NANOS_PER_MILLI) { 764 throw new IllegalArgumentException("bad timeout: millis=" + millis + ",nanos=" + nanos); 765 } 766 767 // avoid overflow: if total > 292,277 years, just wait forever 768 boolean overflow = millis >= (Long.MAX_VALUE - nanos) / NANOS_PER_MILLI; 769 boolean forever = (millis | nanos) == 0; 770 if (forever | overflow) { 771 join(); 772 return; 773 } 774 775 synchronized (lock) { 776 if (!isAlive()) { 777 return; 778 } 779 780 // guaranteed not to overflow 781 long nanosToWait = millis * NANOS_PER_MILLI + nanos; 782 783 // wait until this thread completes or the timeout has elapsed 784 long start = System.nanoTime(); 785 while (true) { 786 lock.wait(millis, nanos); 787 if (!isAlive()) { 788 break; 789 } 790 long nanosElapsed = System.nanoTime() - start; 791 long nanosRemaining = nanosToWait - nanosElapsed; 792 if (nanosRemaining <= 0) { 793 break; 794 } 795 millis = nanosRemaining / NANOS_PER_MILLI; 796 nanos = (int) (nanosRemaining - millis * NANOS_PER_MILLI); 797 } 798 } 799 } 800 801 /** 802 * Throws {@code UnsupportedOperationException}. 803 * @deprecated Only useful in conjunction with deprecated method {@link Thread#suspend}. 804 */ 805 @Deprecated 806 public final void resume() { 807 throw new UnsupportedOperationException(); 808 } 809 810 /** 811 * Calls the <code>run()</code> method of the Runnable object the receiver 812 * holds. If no Runnable is set, does nothing. 813 * 814 * @see Thread#start 815 */ 816 public void run() { 817 if (target != null) { 818 target.run(); 819 } 820 } 821 822 /** 823 * Set the context ClassLoader for the receiver. 824 * 825 * @param cl The context ClassLoader 826 * @see #getContextClassLoader() 827 */ 828 public void setContextClassLoader(ClassLoader cl) { 829 contextClassLoader = cl; 830 } 831 832 /** 833 * Marks this thread as a daemon thread. 834 * A daemon thread only runs as long as there are non-daemon threads running. 835 * When the last non-daemon thread ends, the runtime will exit. This is not 836 * normally relevant to applications with a UI. 837 * @throws IllegalThreadStateException - if this thread has already started. 838 */ 839 public final void setDaemon(boolean isDaemon) { 840 checkNotStarted(); 841 842 if (nativePeer == 0) { 843 daemon = isDaemon; 844 } 845 } 846 847 private void checkNotStarted() { 848 if (hasBeenStarted) { 849 throw new IllegalThreadStateException("Thread already started"); 850 } 851 } 852 853 /** 854 * Sets the default uncaught exception handler. This handler is invoked in 855 * case any Thread dies due to an unhandled exception. 856 * 857 * @param handler 858 * The handler to set or null. 859 */ 860 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) { 861 Thread.defaultUncaughtHandler = handler; 862 } 863 864 /** 865 * Adds a runnable to be invoked upon interruption. If this thread has 866 * already been interrupted, the runnable will be invoked immediately. The 867 * action should be idempotent as it may be invoked multiple times for a 868 * single interruption. 869 * 870 * <p>Each call to this method must be matched with a corresponding call to 871 * {@link #popInterruptAction$}. 872 * 873 * @hide used by NIO 874 */ 875 public final void pushInterruptAction$(Runnable interruptAction) { 876 synchronized (interruptActions) { 877 interruptActions.add(interruptAction); 878 } 879 880 if (interruptAction != null && isInterrupted()) { 881 interruptAction.run(); 882 } 883 } 884 885 /** 886 * Removes {@code interruptAction} so it is not invoked upon interruption. 887 * 888 * @param interruptAction the pushed action, used to check that the call 889 * stack is correctly nested. 890 * 891 * @hide used by NIO 892 */ 893 public final void popInterruptAction$(Runnable interruptAction) { 894 synchronized (interruptActions) { 895 Runnable removed = interruptActions.remove(interruptActions.size() - 1); 896 if (interruptAction != removed) { 897 throw new IllegalArgumentException("Expected " + interruptAction + " but was " + removed); 898 } 899 } 900 } 901 902 /** 903 * Sets the name of the Thread. 904 * 905 * @param threadName the new name for the Thread 906 * @see Thread#getName 907 */ 908 public final void setName(String threadName) { 909 if (threadName == null) { 910 throw new NullPointerException("threadName == null"); 911 } 912 // The lock is taken to ensure no race occurs between starting the 913 // the thread and setting its name (and the name of its native peer). 914 synchronized (this) { 915 this.name = threadName; 916 917 if (isAlive()) { 918 nativeSetName(threadName); 919 } 920 } 921 } 922 923 /** 924 * Tell the VM that the thread's name has changed. This is useful for 925 * DDMS, which would otherwise be oblivious to Thread.setName calls. 926 */ 927 private native void nativeSetName(String newName); 928 929 /** 930 * Sets the priority of this thread. If the requested priority is greater than the 931 * parent thread group's {@link java.lang.ThreadGroup#getMaxPriority}, the group's maximum 932 * priority will be used instead. 933 * 934 * @throws IllegalArgumentException - if the new priority is greater than {@link #MAX_PRIORITY} 935 * or less than {@link #MIN_PRIORITY} 936 */ 937 public final void setPriority(int priority) { 938 if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) { 939 throw new IllegalArgumentException("Priority out of range: " + priority); 940 } 941 942 if (priority > group.getMaxPriority()) { 943 priority = group.getMaxPriority(); 944 } 945 946 // The lock is taken to ensure no race occurs between starting the 947 // the thread and setting its priority (and the priority of its native peer). 948 synchronized (this) { 949 this.priority = priority; 950 951 if (isAlive()) { 952 nativeSetPriority(priority); 953 } 954 } 955 } 956 957 private native void nativeSetPriority(int newPriority); 958 959 /** 960 * <p> 961 * Sets the uncaught exception handler. This handler is invoked in case this 962 * Thread dies due to an unhandled exception. 963 * </p> 964 * 965 * @param handler 966 * The handler to set or <code>null</code>. 967 */ 968 public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) { 969 uncaughtHandler = handler; 970 } 971 972 /** 973 * Causes the thread which sent this message to sleep for the given interval 974 * of time (given in milliseconds). The precision is not guaranteed - the 975 * Thread may sleep more or less than requested. 976 * 977 * @param time 978 * The time to sleep in milliseconds. 979 * @throws InterruptedException if the current thread has been interrupted. 980 * The interrupted status of the current thread will be cleared before the exception 981 * is thrown. 982 * @see Thread#interrupt() 983 */ 984 public static void sleep(long time) throws InterruptedException { 985 Thread.sleep(time, 0); 986 } 987 988 /** 989 * Causes the thread which sent this message to sleep for the given interval 990 * of time (given in milliseconds and nanoseconds). The precision is not 991 * guaranteed - the Thread may sleep more or less than requested. 992 * 993 * @param millis 994 * The time to sleep in milliseconds. 995 * @param nanos 996 * Extra nanosecond precision 997 * @throws InterruptedException if the current thread has been interrupted. 998 * The interrupted status of the current thread will be cleared before the exception 999 * is thrown. 1000 * @see Thread#interrupt() 1001 */ 1002 public static void sleep(long millis, int nanos) throws InterruptedException { 1003 if (millis < 0) { 1004 throw new IllegalArgumentException("millis < 0: " + millis); 1005 } 1006 if (nanos < 0) { 1007 throw new IllegalArgumentException("nanos < 0: " + nanos); 1008 } 1009 if (nanos > 999999) { 1010 throw new IllegalArgumentException("nanos > 999999: " + nanos); 1011 } 1012 1013 // The JLS 3rd edition, section 17.9 says: "...sleep for zero 1014 // time...need not have observable effects." 1015 if (millis == 0 && nanos == 0) { 1016 // ...but we still have to handle being interrupted. 1017 if (Thread.interrupted()) { 1018 throw new InterruptedException(); 1019 } 1020 return; 1021 } 1022 1023 long start = System.nanoTime(); 1024 long duration = (millis * NANOS_PER_MILLI) + nanos; 1025 1026 Object lock = currentThread().lock; 1027 1028 // Wait may return early, so loop until sleep duration passes. 1029 synchronized (lock) { 1030 while (true) { 1031 sleep(lock, millis, nanos); 1032 1033 long now = System.nanoTime(); 1034 long elapsed = now - start; 1035 1036 if (elapsed >= duration) { 1037 break; 1038 } 1039 1040 duration -= elapsed; 1041 start = now; 1042 millis = duration / NANOS_PER_MILLI; 1043 nanos = (int) (duration % NANOS_PER_MILLI); 1044 } 1045 } 1046 } 1047 1048 private static native void sleep(Object lock, long millis, int nanos); 1049 1050 /** 1051 * Starts the new Thread of execution. The <code>run()</code> method of 1052 * the receiver will be called by the receiver Thread itself (and not the 1053 * Thread calling <code>start()</code>). 1054 * 1055 * @throws IllegalThreadStateException - if this thread has already started. 1056 * @see Thread#run 1057 */ 1058 public synchronized void start() { 1059 checkNotStarted(); 1060 1061 hasBeenStarted = true; 1062 1063 nativeCreate(this, stackSize, daemon); 1064 } 1065 1066 private native static void nativeCreate(Thread t, long stackSize, boolean daemon); 1067 1068 /** 1069 * Requests the receiver Thread to stop and throw ThreadDeath. The Thread is 1070 * resumed if it was suspended and awakened if it was sleeping, so that it 1071 * can proceed to throw ThreadDeath. 1072 * 1073 * @deprecated because stopping a thread in this manner is unsafe and can 1074 * leave your application and the VM in an unpredictable state. 1075 */ 1076 @Deprecated 1077 public final void stop() { 1078 stop(new ThreadDeath()); 1079 } 1080 1081 /** 1082 * Throws {@code UnsupportedOperationException}. 1083 * @deprecated because stopping a thread in this manner is unsafe and can 1084 * leave your application and the VM in an unpredictable state. 1085 */ 1086 @Deprecated 1087 public final synchronized void stop(Throwable throwable) { 1088 throw new UnsupportedOperationException(); 1089 } 1090 1091 /** 1092 * Throws {@code UnsupportedOperationException}. 1093 * @deprecated May cause deadlocks. 1094 */ 1095 @Deprecated 1096 public final void suspend() { 1097 throw new UnsupportedOperationException(); 1098 } 1099 1100 /** 1101 * Returns a string containing a concise, human-readable description of the 1102 * Thread. It includes the Thread's name, priority, and group name. 1103 * 1104 * @return a printable representation for the receiver. 1105 */ 1106 @Override 1107 public String toString() { 1108 return "Thread[" + name + "," + priority + "," + group.getName() + "]"; 1109 } 1110 1111 /** 1112 * Causes the calling Thread to yield execution time to another Thread that 1113 * is ready to run. The actual scheduling is implementation-dependent. 1114 */ 1115 public static native void yield(); 1116 1117 /** 1118 * Indicates whether the current Thread has a monitor lock on the specified 1119 * object. 1120 * 1121 * @param object the object to test for the monitor lock 1122 * @return true if the current thread has a monitor lock on the specified 1123 * object; false otherwise 1124 */ 1125 public static boolean holdsLock(Object object) { 1126 return currentThread().nativeHoldsLock(object); 1127 } 1128 1129 private native boolean nativeHoldsLock(Object object); 1130 1131 /** 1132 * Implemented by objects that want to handle cases where a thread is being 1133 * terminated by an uncaught exception. Upon such termination, the handler 1134 * is notified of the terminating thread and causal exception. If there is 1135 * no explicit handler set then the thread's group is the default handler. 1136 */ 1137 public static interface UncaughtExceptionHandler { 1138 /** 1139 * The thread is being terminated by an uncaught exception. Further 1140 * exceptions thrown in this method are prevent the remainder of the 1141 * method from executing, but are otherwise ignored. 1142 * 1143 * @param thread the thread that has an uncaught exception 1144 * @param ex the exception that was thrown 1145 */ 1146 void uncaughtException(Thread thread, Throwable ex); 1147 } 1148 1149 /** 1150 * Unparks this thread. This unblocks the thread it if it was 1151 * previously parked, or indicates that the thread is "preemptively 1152 * unparked" if it wasn't already parked. The latter means that the 1153 * next time the thread is told to park, it will merely clear its 1154 * latent park bit and carry on without blocking. 1155 * 1156 * <p>See {@link java.util.concurrent.locks.LockSupport} for more 1157 * in-depth information of the behavior of this method.</p> 1158 * 1159 * @hide for Unsafe 1160 */ 1161 public void unpark() { 1162 synchronized (lock) { 1163 switch (parkState) { 1164 case ParkState.PREEMPTIVELY_UNPARKED: { 1165 /* 1166 * Nothing to do in this case: By definition, a 1167 * preemptively unparked thread is to remain in 1168 * the preemptively unparked state if it is told 1169 * to unpark. 1170 */ 1171 break; 1172 } 1173 case ParkState.UNPARKED: { 1174 parkState = ParkState.PREEMPTIVELY_UNPARKED; 1175 break; 1176 } 1177 default /*parked*/: { 1178 parkState = ParkState.UNPARKED; 1179 lock.notifyAll(); 1180 break; 1181 } 1182 } 1183 } 1184 } 1185 1186 /** 1187 * Parks the current thread for a particular number of nanoseconds, or 1188 * indefinitely. If not indefinitely, this method unparks the thread 1189 * after the given number of nanoseconds if no other thread unparks it 1190 * first. If the thread has been "preemptively unparked," this method 1191 * cancels that unparking and returns immediately. This method may 1192 * also return spuriously (that is, without the thread being told to 1193 * unpark and without the indicated amount of time elapsing). 1194 * 1195 * <p>See {@link java.util.concurrent.locks.LockSupport} for more 1196 * in-depth information of the behavior of this method.</p> 1197 * 1198 * <p>This method must only be called when <code>this</code> is the current 1199 * thread. 1200 * 1201 * @param nanos number of nanoseconds to park for or <code>0</code> 1202 * to park indefinitely 1203 * @throws IllegalArgumentException thrown if <code>nanos < 0</code> 1204 * 1205 * @hide for Unsafe 1206 */ 1207 public void parkFor(long nanos) { 1208 synchronized (lock) { 1209 switch (parkState) { 1210 case ParkState.PREEMPTIVELY_UNPARKED: { 1211 parkState = ParkState.UNPARKED; 1212 break; 1213 } 1214 case ParkState.UNPARKED: { 1215 long millis = nanos / NANOS_PER_MILLI; 1216 nanos %= NANOS_PER_MILLI; 1217 1218 parkState = ParkState.PARKED; 1219 try { 1220 lock.wait(millis, (int) nanos); 1221 } catch (InterruptedException ex) { 1222 interrupt(); 1223 } finally { 1224 /* 1225 * Note: If parkState manages to become 1226 * PREEMPTIVELY_UNPARKED before hitting this 1227 * code, it should left in that state. 1228 */ 1229 if (parkState == ParkState.PARKED) { 1230 parkState = ParkState.UNPARKED; 1231 } 1232 } 1233 break; 1234 } 1235 default /*parked*/: { 1236 throw new AssertionError("Attempt to repark"); 1237 } 1238 } 1239 } 1240 } 1241 1242 /** 1243 * Parks the current thread until the specified system time. This 1244 * method attempts to unpark the current thread immediately after 1245 * <code>System.currentTimeMillis()</code> reaches the specified 1246 * value, if no other thread unparks it first. If the thread has 1247 * been "preemptively unparked," this method cancels that 1248 * unparking and returns immediately. This method may also return 1249 * spuriously (that is, without the thread being told to unpark 1250 * and without the indicated amount of time elapsing). 1251 * 1252 * <p>See {@link java.util.concurrent.locks.LockSupport} for more 1253 * in-depth information of the behavior of this method.</p> 1254 * 1255 * <p>This method must only be called when <code>this</code> is the 1256 * current thread. 1257 * 1258 * @param time the time after which the thread should be unparked, 1259 * in absolute milliseconds-since-the-epoch 1260 * 1261 * @hide for Unsafe 1262 */ 1263 public void parkUntil(long time) { 1264 synchronized (lock) { 1265 /* 1266 * Note: This conflates the two time bases of "wall clock" 1267 * time and "monotonic uptime" time. However, given that 1268 * the underlying system can only wait on monotonic time, 1269 * it is unclear if there is any way to avoid the 1270 * conflation. The downside here is that if, having 1271 * calculated the delay, the wall clock gets moved ahead, 1272 * this method may not return until well after the wall 1273 * clock has reached the originally designated time. The 1274 * reverse problem (the wall clock being turned back) 1275 * isn't a big deal, since this method is allowed to 1276 * spuriously return for any reason, and this situation 1277 * can safely be construed as just such a spurious return. 1278 */ 1279 long delayMillis = time - System.currentTimeMillis(); 1280 1281 if (delayMillis <= 0) { 1282 parkState = ParkState.UNPARKED; 1283 } else { 1284 parkFor(delayMillis * NANOS_PER_MILLI); 1285 } 1286 } 1287 } 1288 } 1289