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 int 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 <code>interrupt()</code> was called for 716 * the receiver while it was in the <code>join()</code> call 717 * @see Object#notifyAll 718 * @see java.lang.ThreadDeath 719 */ 720 public final void join() throws InterruptedException { 721 synchronized (lock) { 722 while (isAlive()) { 723 lock.wait(); 724 } 725 } 726 } 727 728 /** 729 * Blocks the current Thread (<code>Thread.currentThread()</code>) until 730 * the receiver finishes its execution and dies or the specified timeout 731 * expires, whatever happens first. 732 * 733 * @param millis The maximum time to wait (in milliseconds). 734 * @throws InterruptedException if <code>interrupt()</code> was called for 735 * the receiver while it was in the <code>join()</code> call 736 * @see Object#notifyAll 737 * @see java.lang.ThreadDeath 738 */ 739 public final void join(long millis) throws InterruptedException { 740 join(millis, 0); 741 } 742 743 /** 744 * Blocks the current Thread (<code>Thread.currentThread()</code>) until 745 * the receiver finishes its execution and dies or the specified timeout 746 * expires, whatever happens first. 747 * 748 * @param millis The maximum time to wait (in milliseconds). 749 * @param nanos Extra nanosecond precision 750 * @throws InterruptedException if <code>interrupt()</code> was called for 751 * the receiver while it was in the <code>join()</code> call 752 * @see Object#notifyAll 753 * @see java.lang.ThreadDeath 754 */ 755 public final void join(long millis, int nanos) throws InterruptedException { 756 if (millis < 0 || nanos < 0 || nanos >= NANOS_PER_MILLI) { 757 throw new IllegalArgumentException("bad timeout: millis=" + millis + ",nanos=" + nanos); 758 } 759 760 // avoid overflow: if total > 292,277 years, just wait forever 761 boolean overflow = millis >= (Long.MAX_VALUE - nanos) / NANOS_PER_MILLI; 762 boolean forever = (millis | nanos) == 0; 763 if (forever | overflow) { 764 join(); 765 return; 766 } 767 768 synchronized (lock) { 769 if (!isAlive()) { 770 return; 771 } 772 773 // guaranteed not to overflow 774 long nanosToWait = millis * NANOS_PER_MILLI + nanos; 775 776 // wait until this thread completes or the timeout has elapsed 777 long start = System.nanoTime(); 778 while (true) { 779 lock.wait(millis, nanos); 780 if (!isAlive()) { 781 break; 782 } 783 long nanosElapsed = System.nanoTime() - start; 784 long nanosRemaining = nanosToWait - nanosElapsed; 785 if (nanosRemaining <= 0) { 786 break; 787 } 788 millis = nanosRemaining / NANOS_PER_MILLI; 789 nanos = (int) (nanosRemaining - millis * NANOS_PER_MILLI); 790 } 791 } 792 } 793 794 /** 795 * Throws {@code UnsupportedOperationException}. 796 * @deprecated Only useful in conjunction with deprecated method {@link Thread#suspend}. 797 */ 798 @Deprecated 799 public final void resume() { 800 throw new UnsupportedOperationException(); 801 } 802 803 /** 804 * Calls the <code>run()</code> method of the Runnable object the receiver 805 * holds. If no Runnable is set, does nothing. 806 * 807 * @see Thread#start 808 */ 809 public void run() { 810 if (target != null) { 811 target.run(); 812 } 813 } 814 815 /** 816 * Set the context ClassLoader for the receiver. 817 * 818 * @param cl The context ClassLoader 819 * @see #getContextClassLoader() 820 */ 821 public void setContextClassLoader(ClassLoader cl) { 822 contextClassLoader = cl; 823 } 824 825 /** 826 * Marks this thread as a daemon thread. 827 * A daemon thread only runs as long as there are non-daemon threads running. 828 * When the last non-daemon thread ends, the runtime will exit. This is not 829 * normally relevant to applications with a UI. 830 * @throws IllegalThreadStateException - if this thread has already started. 831 */ 832 public final void setDaemon(boolean isDaemon) { 833 checkNotStarted(); 834 835 if (nativePeer == 0) { 836 daemon = isDaemon; 837 } 838 } 839 840 private void checkNotStarted() { 841 if (hasBeenStarted) { 842 throw new IllegalThreadStateException("Thread already started"); 843 } 844 } 845 846 /** 847 * Sets the default uncaught exception handler. This handler is invoked in 848 * case any Thread dies due to an unhandled exception. 849 * 850 * @param handler 851 * The handler to set or null. 852 */ 853 public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) { 854 Thread.defaultUncaughtHandler = handler; 855 } 856 857 /** 858 * Adds a runnable to be invoked upon interruption. If this thread has 859 * already been interrupted, the runnable will be invoked immediately. The 860 * action should be idempotent as it may be invoked multiple times for a 861 * single interruption. 862 * 863 * <p>Each call to this method must be matched with a corresponding call to 864 * {@link #popInterruptAction$}. 865 * 866 * @hide used by NIO 867 */ 868 public final void pushInterruptAction$(Runnable interruptAction) { 869 synchronized (interruptActions) { 870 interruptActions.add(interruptAction); 871 } 872 873 if (interruptAction != null && isInterrupted()) { 874 interruptAction.run(); 875 } 876 } 877 878 /** 879 * Removes {@code interruptAction} so it is not invoked upon interruption. 880 * 881 * @param interruptAction the pushed action, used to check that the call 882 * stack is correctly nested. 883 * 884 * @hide used by NIO 885 */ 886 public final void popInterruptAction$(Runnable interruptAction) { 887 synchronized (interruptActions) { 888 Runnable removed = interruptActions.remove(interruptActions.size() - 1); 889 if (interruptAction != removed) { 890 throw new IllegalArgumentException("Expected " + interruptAction + " but was " + removed); 891 } 892 } 893 } 894 895 /** 896 * Sets the name of the Thread. 897 * 898 * @param threadName the new name for the Thread 899 * @see Thread#getName 900 */ 901 public final void setName(String threadName) { 902 if (threadName == null) { 903 throw new NullPointerException("threadName == null"); 904 } 905 // The lock is taken to ensure no race occurs between starting the 906 // the thread and setting its name (and the name of its native peer). 907 synchronized (this) { 908 this.name = threadName; 909 910 if (isAlive()) { 911 nativeSetName(threadName); 912 } 913 } 914 } 915 916 /** 917 * Tell the VM that the thread's name has changed. This is useful for 918 * DDMS, which would otherwise be oblivious to Thread.setName calls. 919 */ 920 private native void nativeSetName(String newName); 921 922 /** 923 * Sets the priority of this thread. If the requested priority is greater than the 924 * parent thread group's {@link java.lang.ThreadGroup#getMaxPriority}, the group's maximum 925 * priority will be used instead. 926 * 927 * @throws IllegalArgumentException - if the new priority is greater than {@link #MAX_PRIORITY} 928 * or less than {@link #MIN_PRIORITY} 929 */ 930 public final void setPriority(int priority) { 931 if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) { 932 throw new IllegalArgumentException("Priority out of range: " + priority); 933 } 934 935 if (priority > group.getMaxPriority()) { 936 priority = group.getMaxPriority(); 937 } 938 939 // The lock is taken to ensure no race occurs between starting the 940 // the thread and setting its priority (and the priority of its native peer). 941 synchronized (this) { 942 this.priority = priority; 943 944 if (isAlive()) { 945 nativeSetPriority(priority); 946 } 947 } 948 } 949 950 private native void nativeSetPriority(int newPriority); 951 952 /** 953 * <p> 954 * Sets the uncaught exception handler. This handler is invoked in case this 955 * Thread dies due to an unhandled exception. 956 * </p> 957 * 958 * @param handler 959 * The handler to set or <code>null</code>. 960 */ 961 public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) { 962 uncaughtHandler = handler; 963 } 964 965 /** 966 * Causes the thread which sent this message to sleep for the given interval 967 * of time (given in milliseconds). The precision is not guaranteed - the 968 * Thread may sleep more or less than requested. 969 * 970 * @param time 971 * The time to sleep in milliseconds. 972 * @throws InterruptedException 973 * if <code>interrupt()</code> was called for this Thread while 974 * it was sleeping 975 * @see Thread#interrupt() 976 */ 977 public static void sleep(long time) throws InterruptedException { 978 Thread.sleep(time, 0); 979 } 980 981 /** 982 * Causes the thread which sent this message to sleep for the given interval 983 * of time (given in milliseconds and nanoseconds). The precision is not 984 * guaranteed - the Thread may sleep more or less than requested. 985 * 986 * @param millis 987 * The time to sleep in milliseconds. 988 * @param nanos 989 * Extra nanosecond precision 990 * @throws InterruptedException 991 * if <code>interrupt()</code> was called for this Thread while 992 * it was sleeping 993 * @see Thread#interrupt() 994 */ 995 public static void sleep(long millis, int nanos) throws InterruptedException { 996 // The JLS 3rd edition, section 17.9 says: "...sleep for zero 997 // time...need not have observable effects." 998 if (millis == 0 && nanos == 0) { 999 return; 1000 } 1001 1002 long start = System.nanoTime(); 1003 long duration = (millis * NANOS_PER_MILLI) + nanos; 1004 1005 Object lock = currentThread().lock; 1006 1007 // Wait may return early, so loop until sleep duration passes. 1008 synchronized (lock) { 1009 while (true) { 1010 sleep(lock, millis, nanos); 1011 1012 long now = System.nanoTime(); 1013 long elapsed = now - start; 1014 1015 if (elapsed >= duration) { 1016 break; 1017 } 1018 1019 duration -= elapsed; 1020 start = now; 1021 millis = duration / NANOS_PER_MILLI; 1022 nanos = (int) (duration % NANOS_PER_MILLI); 1023 } 1024 } 1025 } 1026 1027 private static native void sleep(Object lock, long millis, int nanos); 1028 1029 /** 1030 * Starts the new Thread of execution. The <code>run()</code> method of 1031 * the receiver will be called by the receiver Thread itself (and not the 1032 * Thread calling <code>start()</code>). 1033 * 1034 * @throws IllegalThreadStateException - if this thread has already started. 1035 * @see Thread#run 1036 */ 1037 public synchronized void start() { 1038 checkNotStarted(); 1039 1040 hasBeenStarted = true; 1041 1042 nativeCreate(this, stackSize, daemon); 1043 } 1044 1045 private native static void nativeCreate(Thread t, long stackSize, boolean daemon); 1046 1047 /** 1048 * Requests the receiver Thread to stop and throw ThreadDeath. The Thread is 1049 * resumed if it was suspended and awakened if it was sleeping, so that it 1050 * can proceed to throw ThreadDeath. 1051 * 1052 * @deprecated because stopping a thread in this manner is unsafe and can 1053 * leave your application and the VM in an unpredictable state. 1054 */ 1055 @Deprecated 1056 public final void stop() { 1057 stop(new ThreadDeath()); 1058 } 1059 1060 /** 1061 * Throws {@code UnsupportedOperationException}. 1062 * @deprecated because stopping a thread in this manner is unsafe and can 1063 * leave your application and the VM in an unpredictable state. 1064 */ 1065 @Deprecated 1066 public final synchronized void stop(Throwable throwable) { 1067 throw new UnsupportedOperationException(); 1068 } 1069 1070 /** 1071 * Throws {@code UnsupportedOperationException}. 1072 * @deprecated May cause deadlocks. 1073 */ 1074 @Deprecated 1075 public final void suspend() { 1076 throw new UnsupportedOperationException(); 1077 } 1078 1079 /** 1080 * Returns a string containing a concise, human-readable description of the 1081 * Thread. It includes the Thread's name, priority, and group name. 1082 * 1083 * @return a printable representation for the receiver. 1084 */ 1085 @Override 1086 public String toString() { 1087 return "Thread[" + name + "," + priority + "," + group.getName() + "]"; 1088 } 1089 1090 /** 1091 * Causes the calling Thread to yield execution time to another Thread that 1092 * is ready to run. The actual scheduling is implementation-dependent. 1093 */ 1094 public static native void yield(); 1095 1096 /** 1097 * Indicates whether the current Thread has a monitor lock on the specified 1098 * object. 1099 * 1100 * @param object the object to test for the monitor lock 1101 * @return true if the current thread has a monitor lock on the specified 1102 * object; false otherwise 1103 */ 1104 public static boolean holdsLock(Object object) { 1105 return currentThread().nativeHoldsLock(object); 1106 } 1107 1108 private native boolean nativeHoldsLock(Object object); 1109 1110 /** 1111 * Implemented by objects that want to handle cases where a thread is being 1112 * terminated by an uncaught exception. Upon such termination, the handler 1113 * is notified of the terminating thread and causal exception. If there is 1114 * no explicit handler set then the thread's group is the default handler. 1115 */ 1116 public static interface UncaughtExceptionHandler { 1117 /** 1118 * The thread is being terminated by an uncaught exception. Further 1119 * exceptions thrown in this method are prevent the remainder of the 1120 * method from executing, but are otherwise ignored. 1121 * 1122 * @param thread the thread that has an uncaught exception 1123 * @param ex the exception that was thrown 1124 */ 1125 void uncaughtException(Thread thread, Throwable ex); 1126 } 1127 1128 /** 1129 * Unparks this thread. This unblocks the thread it if it was 1130 * previously parked, or indicates that the thread is "preemptively 1131 * unparked" if it wasn't already parked. The latter means that the 1132 * next time the thread is told to park, it will merely clear its 1133 * latent park bit and carry on without blocking. 1134 * 1135 * <p>See {@link java.util.concurrent.locks.LockSupport} for more 1136 * in-depth information of the behavior of this method.</p> 1137 * 1138 * @hide for Unsafe 1139 */ 1140 public void unpark() { 1141 synchronized (lock) { 1142 switch (parkState) { 1143 case ParkState.PREEMPTIVELY_UNPARKED: { 1144 /* 1145 * Nothing to do in this case: By definition, a 1146 * preemptively unparked thread is to remain in 1147 * the preemptively unparked state if it is told 1148 * to unpark. 1149 */ 1150 break; 1151 } 1152 case ParkState.UNPARKED: { 1153 parkState = ParkState.PREEMPTIVELY_UNPARKED; 1154 break; 1155 } 1156 default /*parked*/: { 1157 parkState = ParkState.UNPARKED; 1158 lock.notifyAll(); 1159 break; 1160 } 1161 } 1162 } 1163 } 1164 1165 /** 1166 * Parks the current thread for a particular number of nanoseconds, or 1167 * indefinitely. If not indefinitely, this method unparks the thread 1168 * after the given number of nanoseconds if no other thread unparks it 1169 * first. If the thread has been "preemptively unparked," this method 1170 * cancels that unparking and returns immediately. This method may 1171 * also return spuriously (that is, without the thread being told to 1172 * unpark and without the indicated amount of time elapsing). 1173 * 1174 * <p>See {@link java.util.concurrent.locks.LockSupport} for more 1175 * in-depth information of the behavior of this method.</p> 1176 * 1177 * <p>This method must only be called when <code>this</code> is the current 1178 * thread. 1179 * 1180 * @param nanos number of nanoseconds to park for or <code>0</code> 1181 * to park indefinitely 1182 * @throws IllegalArgumentException thrown if <code>nanos < 0</code> 1183 * 1184 * @hide for Unsafe 1185 */ 1186 public void parkFor(long nanos) { 1187 synchronized (lock) { 1188 switch (parkState) { 1189 case ParkState.PREEMPTIVELY_UNPARKED: { 1190 parkState = ParkState.UNPARKED; 1191 break; 1192 } 1193 case ParkState.UNPARKED: { 1194 long millis = nanos / NANOS_PER_MILLI; 1195 nanos %= NANOS_PER_MILLI; 1196 1197 parkState = ParkState.PARKED; 1198 try { 1199 lock.wait(millis, (int) nanos); 1200 } catch (InterruptedException ex) { 1201 interrupt(); 1202 } finally { 1203 /* 1204 * Note: If parkState manages to become 1205 * PREEMPTIVELY_UNPARKED before hitting this 1206 * code, it should left in that state. 1207 */ 1208 if (parkState == ParkState.PARKED) { 1209 parkState = ParkState.UNPARKED; 1210 } 1211 } 1212 break; 1213 } 1214 default /*parked*/: { 1215 throw new AssertionError("Attempt to repark"); 1216 } 1217 } 1218 } 1219 } 1220 1221 /** 1222 * Parks the current thread until the specified system time. This 1223 * method attempts to unpark the current thread immediately after 1224 * <code>System.currentTimeMillis()</code> reaches the specified 1225 * value, if no other thread unparks it first. If the thread has 1226 * been "preemptively unparked," this method cancels that 1227 * unparking and returns immediately. This method may also return 1228 * spuriously (that is, without the thread being told to unpark 1229 * and without the indicated amount of time elapsing). 1230 * 1231 * <p>See {@link java.util.concurrent.locks.LockSupport} for more 1232 * in-depth information of the behavior of this method.</p> 1233 * 1234 * <p>This method must only be called when <code>this</code> is the 1235 * current thread. 1236 * 1237 * @param time the time after which the thread should be unparked, 1238 * in absolute milliseconds-since-the-epoch 1239 * 1240 * @hide for Unsafe 1241 */ 1242 public void parkUntil(long time) { 1243 synchronized (lock) { 1244 /* 1245 * Note: This conflates the two time bases of "wall clock" 1246 * time and "monotonic uptime" time. However, given that 1247 * the underlying system can only wait on monotonic time, 1248 * it is unclear if there is any way to avoid the 1249 * conflation. The downside here is that if, having 1250 * calculated the delay, the wall clock gets moved ahead, 1251 * this method may not return until well after the wall 1252 * clock has reached the originally designated time. The 1253 * reverse problem (the wall clock being turned back) 1254 * isn't a big deal, since this method is allowed to 1255 * spuriously return for any reason, and this situation 1256 * can safely be construed as just such a spurious return. 1257 */ 1258 long delayMillis = time - System.currentTimeMillis(); 1259 1260 if (delayMillis <= 0) { 1261 parkState = ParkState.UNPARKED; 1262 } else { 1263 parkFor(delayMillis * NANOS_PER_MILLI); 1264 } 1265 } 1266 } 1267 } 1268