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