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