1. /*
  2. * @(#)Thread.java 1.99 02/04/18
  3. *
  4. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.lang;
  8. import java.security.AccessController;
  9. import java.security.AccessControlContext;
  10. /**
  11. * A <i>thread</i> is a thread of execution in a program. The Java
  12. * Virtual Machine allows an application to have multiple threads of
  13. * execution running concurrently.
  14. * <p>
  15. * Every thread has a priority. Threads with higher priority are
  16. * executed in preference to threads with lower priority. Each thread
  17. * may or may not also be marked as a daemon. When code running in
  18. * some thread creates a new <code>Thread</code> object, the new
  19. * thread has its priority initially set equal to the priority of the
  20. * creating thread, and is a daemon thread if and only if the
  21. * creating thread is a daemon.
  22. * <p>
  23. * When a Java Virtual Machine starts up, there is usually a single
  24. * non-daemon thread (which typically calls the method named
  25. * <code>main</code> of some designated class). The Java Virtual
  26. * Machine continues to execute threads until either of the following
  27. * occurs:
  28. * <ul>
  29. * <li>The <code>exit</code> method of class <code>Runtime</code> has been
  30. * called and the security manager has permitted the exit operation
  31. * to take place.
  32. * <li>All threads that are not daemon threads have died, either by
  33. * returning from the call to the <code>run</code> method or by
  34. * throwing an exception that propagates beyond the <code>run</code>
  35. * method.
  36. * </ul>
  37. * <p>
  38. * There are two ways to create a new thread of execution. One is to
  39. * declare a class to be a subclass of <code>Thread</code>. This
  40. * subclass should override the <code>run</code> method of class
  41. * <code>Thread</code>. An instance of the subclass can then be
  42. * allocated and started. For example, a thread that computes primes
  43. * larger than a stated value could be written as follows:
  44. * <p><hr><blockquote><pre>
  45. * class PrimeThread extends Thread {
  46. * long minPrime;
  47. * PrimeThread(long minPrime) {
  48. * this.minPrime = minPrime;
  49. * }
  50. *
  51. * public void run() {
  52. * // compute primes larger than minPrime
  53. *  . . .
  54. * }
  55. * }
  56. * </pre></blockquote><hr>
  57. * <p>
  58. * The following code would then create a thread and start it running:
  59. * <p><blockquote><pre>
  60. * PrimeThread p = new PrimeThread(143);
  61. * p.start();
  62. * </pre></blockquote>
  63. * <p>
  64. * The other way to create a thread is to declare a class that
  65. * implements the <code>Runnable</code> interface. That class then
  66. * implements the <code>run</code> method. An instance of the class can
  67. * then be allocated, passed as an argument when creating
  68. * <code>Thread</code>, and started. The same example in this other
  69. * style looks like the following:
  70. * <p><hr><blockquote><pre>
  71. * class PrimeRun implements Runnable {
  72. * long minPrime;
  73. * PrimeRun(long minPrime) {
  74. * this.minPrime = minPrime;
  75. * }
  76. *
  77. * public void run() {
  78. * // compute primes larger than minPrime
  79. *  . . .
  80. * }
  81. * }
  82. * </pre></blockquote><hr>
  83. * <p>
  84. * The following code would then create a thread and start it running:
  85. * <p><blockquote><pre>
  86. * PrimeRun p = new PrimeRun(143);
  87. * new Thread(p).start();
  88. * </pre></blockquote>
  89. * <p>
  90. * Every thread has a name for identification purposes. More than
  91. * one thread may have the same name. If a name is not specified when
  92. * a thread is created, a new name is generated for it.
  93. *
  94. * @author unascribed
  95. * @version 1.99, 04/18/02
  96. * @see java.lang.Runnable
  97. * @see java.lang.Runtime#exit(int)
  98. * @see java.lang.Thread#run()
  99. * @see java.lang.Thread#stop()
  100. * @since JDK1.0
  101. */
  102. public
  103. class Thread implements Runnable {
  104. /* Make sure registerNatives is the first thing <clinit> does. */
  105. private static native void registerNatives();
  106. static {
  107. registerNatives();
  108. }
  109. private char name[];
  110. private int priority;
  111. private Thread threadQ;
  112. private long eetop;
  113. /* Whether or not to single_step this thread. */
  114. private boolean single_step;
  115. /* Whether or not the thread is a daemon thread. */
  116. private boolean daemon = false;
  117. /* Whether or not this thread was asked to exit before it runs.*/
  118. private boolean stillborn = false;
  119. /* What will be run. */
  120. private Runnable target;
  121. /* The group of this thread */
  122. private ThreadGroup group;
  123. /* The context ClassLoader for this thread */
  124. private ClassLoader contextClassLoader;
  125. /* The inherited AccessControlContext of this thread */
  126. private AccessControlContext inheritedAccessControlContext;
  127. /* For autonumbering anonymous threads. */
  128. private static int threadInitNumber;
  129. private static synchronized int nextThreadNum() {
  130. return threadInitNumber++;
  131. }
  132. // static permissions
  133. private static RuntimePermission stopThreadPermission;
  134. /* ThreadLocal values pertaining to this thread. This map is maintained
  135. * by the ThreadLocal class. */
  136. ThreadLocal.ThreadLocalMap threadLocals = null;
  137. /*
  138. * InheritableThreadLocal values pertaining to this thread. This map is
  139. * maintained by the InheritableThreadLocal class.
  140. */
  141. ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
  142. /**
  143. * The minimum priority that a thread can have.
  144. */
  145. public final static int MIN_PRIORITY = 1;
  146. /**
  147. * The default priority that is assigned to a thread.
  148. */
  149. public final static int NORM_PRIORITY = 5;
  150. /**
  151. * The maximum priority that a thread can have.
  152. */
  153. public final static int MAX_PRIORITY = 10;
  154. /**
  155. * Returns a reference to the currently executing thread object.
  156. *
  157. * @return the currently executing thread.
  158. */
  159. public static native Thread currentThread();
  160. /**
  161. * Causes the currently executing thread object to temporarily pause
  162. * and allow other threads to execute.
  163. */
  164. public static native void yield();
  165. /**
  166. * Causes the currently executing thread to sleep (temporarily cease
  167. * execution) for the specified number of milliseconds. The thread
  168. * does not lose ownership of any monitors.
  169. *
  170. * @param millis the length of time to sleep in milliseconds.
  171. * @exception InterruptedException if another thread has interrupted
  172. * the current thread. The <i>interrupted status</i> of the
  173. * current thread is cleared when this exception is thrown.
  174. * @see java.lang.Object#notify()
  175. */
  176. public static native void sleep(long millis) throws InterruptedException;
  177. /**
  178. * Causes the currently executing thread to sleep (cease execution)
  179. * for the specified number of milliseconds plus the specified number
  180. * of nanoseconds. The thread does not lose ownership of any monitors.
  181. *
  182. * @param millis the length of time to sleep in milliseconds.
  183. * @param nanos 0-999999 additional nanoseconds to sleep.
  184. * @exception IllegalArgumentException if the value of millis is
  185. * negative or the value of nanos is not in the range
  186. * 0-999999.
  187. * @exception InterruptedException if another thread has interrupted
  188. * the current thread. The <i>interrupted status</i> of the
  189. * current thread is cleared when this exception is thrown.
  190. * @see java.lang.Object#notify()
  191. */
  192. public static void sleep(long millis, int nanos)
  193. throws InterruptedException {
  194. if (millis < 0) {
  195. throw new IllegalArgumentException("timeout value is negative");
  196. }
  197. if (nanos < 0 || nanos > 999999) {
  198. throw new IllegalArgumentException(
  199. "nanosecond timeout value out of range");
  200. }
  201. if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  202. millis++;
  203. }
  204. sleep(millis);
  205. }
  206. /**
  207. * Initialize a Thread.
  208. *
  209. * @param g the Thread group
  210. * @param target the object whose run() method gets called
  211. * @param name the name of the new Thread
  212. */
  213. private void init(ThreadGroup g, Runnable target, String name){
  214. Thread parent = currentThread();
  215. if (g == null) {
  216. /* Determine if it's an applet or not */
  217. SecurityManager security = System.getSecurityManager();
  218. /* If there is a security manager, ask the security manager
  219. what to do. */
  220. if (security != null) {
  221. g = security.getThreadGroup();
  222. }
  223. /* If the security doesn't have a strong opinion of the matter
  224. use the parent thread group. */
  225. if (g == null) {
  226. g = parent.getThreadGroup();
  227. }
  228. }
  229. /* checkAccess regardless of whether or not threadgroup is
  230. explicitly passed in. */
  231. g.checkAccess();
  232. this.group = g;
  233. this.daemon = parent.isDaemon();
  234. this.priority = parent.getPriority();
  235. this.name = name.toCharArray();
  236. this.contextClassLoader = parent.contextClassLoader;
  237. this.inheritedAccessControlContext = AccessController.getContext();
  238. this.target = target;
  239. setPriority(priority);
  240. if (parent.inheritableThreadLocals != null)
  241. this.inheritableThreadLocals =
  242. ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
  243. g.add(this);
  244. }
  245. /**
  246. * Allocates a new <code>Thread</code> object. This constructor has
  247. * the same effect as <code>Thread(null, null,</code>
  248. * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
  249. * a newly generated name. Automatically generated names are of the
  250. * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
  251. * <p>
  252. * Threads created this way must have overridden their
  253. * <code>run()</code> method to actually do anything. An example
  254. * illustrating this method being used follows:
  255. * <p><blockquote><pre>
  256. * import java.lang.*;
  257. *
  258. * class plain01 implements Runnable {
  259. * String name;
  260. * plain01() {
  261. * name = null;
  262. * }
  263. * plain01(String s) {
  264. * name = s;
  265. * }
  266. * public void run() {
  267. * if (name == null)
  268. * System.out.println("A new thread created");
  269. * else
  270. * System.out.println("A new thread with name " + name +
  271. * " created");
  272. * }
  273. * }
  274. * class threadtest01 {
  275. * public static void main(String args[] ) {
  276. * int failed = 0 ;
  277. *
  278. * <b>Thread t1 = new Thread();</b>
  279. * if (t1 != null)
  280. * System.out.println("new Thread() succeed");
  281. * else {
  282. * System.out.println("new Thread() failed");
  283. * failed++;
  284. * }
  285. * }
  286. * }
  287. * </pre></blockquote>
  288. *
  289. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  290. * java.lang.Runnable, java.lang.String)
  291. */
  292. public Thread() {
  293. init(null, null, "Thread-" + nextThreadNum());
  294. }
  295. /**
  296. * Allocates a new <code>Thread</code> object. This constructor has
  297. * the same effect as <code>Thread(null, target,</code>
  298. * <i>gname</i><code>)</code>, where <i>gname</i> is
  299. * a newly generated name. Automatically generated names are of the
  300. * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
  301. *
  302. * @param target the object whose <code>run</code> method is called.
  303. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  304. * java.lang.Runnable, java.lang.String)
  305. */
  306. public Thread(Runnable target) {
  307. init(null, target, "Thread-" + nextThreadNum());
  308. }
  309. /**
  310. * Allocates a new <code>Thread</code> object. This constructor has
  311. * the same effect as <code>Thread(group, target,</code>
  312. * <i>gname</i><code>)</code>, where <i>gname</i> is
  313. * a newly generated name. Automatically generated names are of the
  314. * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
  315. *
  316. * @param group the thread group.
  317. * @param target the object whose <code>run</code> method is called.
  318. * @exception SecurityException if the current thread cannot create a
  319. * thread in the specified thread group.
  320. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  321. * java.lang.Runnable, java.lang.String)
  322. */
  323. public Thread(ThreadGroup group, Runnable target) {
  324. init(group, target, "Thread-" + nextThreadNum());
  325. }
  326. /**
  327. * Allocates a new <code>Thread</code> object. This constructor has
  328. * the same effect as <code>Thread(null, null, name)</code>.
  329. *
  330. * @param name the name of the new thread.
  331. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  332. * java.lang.Runnable, java.lang.String)
  333. */
  334. public Thread(String name) {
  335. init(null, null, name);
  336. }
  337. /**
  338. * Allocates a new <code>Thread</code> object. This constructor has
  339. * the same effect as <code>Thread(group, null, name)</code>
  340. *
  341. * @param group the thread group.
  342. * @param name the name of the new thread.
  343. * @exception SecurityException if the current thread cannot create a
  344. * thread in the specified thread group.
  345. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  346. * java.lang.Runnable, java.lang.String)
  347. */
  348. public Thread(ThreadGroup group, String name) {
  349. init(group, null, name);
  350. }
  351. /**
  352. * Allocates a new <code>Thread</code> object. This constructor has
  353. * the same effect as <code>Thread(null, target, name)</code>.
  354. *
  355. * @param target the object whose <code>run</code> method is called.
  356. * @param name the name of the new thread.
  357. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  358. * java.lang.Runnable, java.lang.String)
  359. */
  360. public Thread(Runnable target, String name) {
  361. init(null, target, name);
  362. }
  363. /**
  364. * Allocates a new <code>Thread</code> object so that it has
  365. * <code>target</code> as its run object, has the specified
  366. * <code>name</code> as its name, and belongs to the thread group
  367. * referred to by <code>group</code>.
  368. * <p>
  369. * If <code>group</code> is <code>null</code>, the group is
  370. * set to be the same ThreadGroup as
  371. * the thread that is creating the new thread.
  372. *
  373. * <p>If there is a security manager, its <code>checkAccess</code>
  374. * method is called with the ThreadGroup as its argument.
  375. * This may result in a SecurityException.
  376. * <p>
  377. * If the <code>target</code> argument is not <code>null</code>, the
  378. * <code>run</code> method of the <code>target</code> is called when
  379. * this thread is started. If the target argument is
  380. * <code>null</code>, this thread's <code>run</code> method is called
  381. * when this thread is started.
  382. * <p>
  383. * The priority of the newly created thread is set equal to the
  384. * priority of the thread creating it, that is, the currently running
  385. * thread. The method <code>setPriority</code> may be used to
  386. * change the priority to a new value.
  387. * <p>
  388. * The newly created thread is initially marked as being a daemon
  389. * thread if and only if the thread creating it is currently marked
  390. * as a daemon thread. The method <code>setDaemon </code> may be used
  391. * to change whether or not a thread is a daemon.
  392. *
  393. * @param group the thread group.
  394. * @param target the object whose <code>run</code> method is called.
  395. * @param name the name of the new thread.
  396. * @exception SecurityException if the current thread cannot create a
  397. * thread in the specified thread group.
  398. * @see java.lang.Runnable#run()
  399. * @see java.lang.Thread#run()
  400. * @see java.lang.Thread#setDaemon(boolean)
  401. * @see java.lang.Thread#setPriority(int)
  402. * @see java.lang.ThreadGroup#checkAccess()
  403. * @see SecurityManager#checkAccess
  404. */
  405. public Thread(ThreadGroup group, Runnable target, String name) {
  406. init(group, target, name);
  407. }
  408. /**
  409. * Causes this thread to begin execution; the Java Virtual Machine
  410. * calls the <code>run</code> method of this thread.
  411. * <p>
  412. * The result is that two threads are running concurrently: the
  413. * current thread (which returns from the call to the
  414. * <code>start</code> method) and the other thread (which executes its
  415. * <code>run</code> method).
  416. *
  417. * @exception IllegalThreadStateException if the thread was already
  418. * started.
  419. * @see java.lang.Thread#run()
  420. * @see java.lang.Thread#stop()
  421. */
  422. public synchronized native void start();
  423. /**
  424. * If this thread was constructed using a separate
  425. * <code>Runnable</code> run object, then that
  426. * <code>Runnable</code> object's <code>run</code> method is called;
  427. * otherwise, this method does nothing and returns.
  428. * <p>
  429. * Subclasses of <code>Thread</code> should override this method.
  430. *
  431. * @see java.lang.Thread#start()
  432. * @see java.lang.Thread#stop()
  433. * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
  434. * java.lang.Runnable, java.lang.String)
  435. * @see java.lang.Runnable#run()
  436. */
  437. public void run() {
  438. if (target != null) {
  439. target.run();
  440. }
  441. }
  442. /**
  443. * This method is called by the system to give a Thread
  444. * a chance to clean up before it actually exits.
  445. */
  446. private void exit() {
  447. if (group != null) {
  448. group.remove(this);
  449. group = null;
  450. }
  451. /* Aggressively null object connected to Thread: see bug 4006245 */
  452. target = null;
  453. }
  454. /**
  455. * Forces the thread to stop executing.
  456. * <p>
  457. * If there is a security manager installed, its <code>checkAccess</code>
  458. * method is called with <code>this</code>
  459. * as its argument. This may result in a
  460. * <code>SecurityException</code> being raised (in the current thread).
  461. * <p>
  462. * If this thread is different from the current thread (that is, the current
  463. * thread is trying to stop a thread other than itself), the
  464. * security manager's <code>checkPermission</code> method (with a
  465. * <code>RuntimePermission("stopThread")</code> argument) is called in
  466. * addition.
  467. * Again, this may result in throwing a
  468. * <code>SecurityException</code> (in the current thread).
  469. * <p>
  470. * The thread represented by this thread is forced to stop whatever
  471. * it is doing abnormally and to throw a newly created
  472. * <code>ThreadDeath</code> object as an exception.
  473. * <p>
  474. * It is permitted to stop a thread that has not yet been started.
  475. * If the thread is eventually started, it immediately terminates.
  476. * <p>
  477. * An application should not normally try to catch
  478. * <code>ThreadDeath</code> unless it must do some extraordinary
  479. * cleanup operation (note that the throwing of
  480. * <code>ThreadDeath</code> causes <code>finally</code> clauses of
  481. * <code>try</code> statements to be executed before the thread
  482. * officially dies). If a <code>catch</code> clause catches a
  483. * <code>ThreadDeath</code> object, it is important to rethrow the
  484. * object so that the thread actually dies.
  485. * <p>
  486. * The top-level error handler that reacts to otherwise uncaught
  487. * exceptions does not print out a message or otherwise notify the
  488. * application if the uncaught exception is an instance of
  489. * <code>ThreadDeath</code>.
  490. *
  491. * @exception SecurityException if the current thread cannot
  492. * modify this thread.
  493. * @see java.lang.Thread#interrupt()
  494. * @see java.lang.Thread#checkAccess()
  495. * @see java.lang.Thread#run()
  496. * @see java.lang.Thread#start()
  497. * @see java.lang.ThreadDeath
  498. * @see java.lang.ThreadGroup#uncaughtException(java.lang.Thread,
  499. * java.lang.Throwable)
  500. * @see SecurityManager#checkAccess(Thread)
  501. * @see SecurityManager#checkPermission
  502. * @deprecated This method is inherently unsafe. Stopping a thread with
  503. * Thread.stop causes it to unlock all of the monitors that it
  504. * has locked (as a natural consequence of the unchecked
  505. * <code>ThreadDeath</code> exception propagating up the stack). If
  506. * any of the objects previously protected by these monitors were in
  507. * an inconsistent state, the damaged objects become visible to
  508. * other threads, potentially resulting in arbitrary behavior. Many
  509. * uses of <code>stop</code> should be replaced by code that simply
  510. * modifies some variable to indicate that the target thread should
  511. * stop running. The target thread should check this variable
  512. * regularly, and return from its run method in an orderly fashion
  513. * if the variable indicates that it is to stop running. If the
  514. * target thread waits for long periods (on a condition variable,
  515. * for example), the <code>interrupt</code> method should be used to
  516. * interrupt the wait.
  517. * For more information, see
  518. * <a href="../../../guide/misc/threadPrimitiveDeprecation.html">Why
  519. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  520. */
  521. public final void stop() {
  522. synchronized (this) {
  523. SecurityManager security = System.getSecurityManager();
  524. if (security != null) {
  525. checkAccess();
  526. if (this != Thread.currentThread()) {
  527. if (stopThreadPermission == null)
  528. stopThreadPermission =
  529. new RuntimePermission("stopThread");
  530. security.checkPermission(stopThreadPermission);
  531. }
  532. }
  533. resume(); // Wake up thread if it was suspended; no-op otherwise
  534. stop0(new ThreadDeath());
  535. }
  536. }
  537. /**
  538. * Forces the thread to stop executing.
  539. * <p>
  540. * If there is a security manager installed, the <code>checkAccess</code>
  541. * method of this thread is called, which may result in a
  542. * <code>SecurityException</code> being raised (in the current thread).
  543. * <p>
  544. * If this thread is different from the current thread (that is, the current
  545. * thread is trying to stop a thread other than itself) or
  546. * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
  547. * security manager's <code>checkPermission</code> method (with the
  548. * <code>RuntimePermission("stopThread")</code> argument) is called in
  549. * addition.
  550. * Again, this may result in throwing a
  551. * <code>SecurityException</code> (in the current thread).
  552. * <p>
  553. * If the argument <code>obj</code> is null, a
  554. * <code>NullPointerException</code> is thrown (in the current thread).
  555. * <p>
  556. * The thread represented by this thread is forced to complete
  557. * whatever it is doing abnormally and to throw the
  558. * <code>Throwable</code> object <code>obj</code> as an exception. This
  559. * is an unusual action to take; normally, the <code>stop</code> method
  560. * that takes no arguments should be used.
  561. * <p>
  562. * It is permitted to stop a thread that has not yet been started.
  563. * If the thread is eventually started, it immediately terminates.
  564. *
  565. * @param obj the Throwable object to be thrown.
  566. * @exception SecurityException if the current thread cannot modify
  567. * this thread.
  568. * @see java.lang.Thread#interrupt()
  569. * @see java.lang.Thread#checkAccess()
  570. * @see java.lang.Thread#run()
  571. * @see java.lang.Thread#start()
  572. * @see java.lang.Thread#stop()
  573. * @see SecurityManager#checkAccess(Thread)
  574. * @see SecurityManager#checkPermission
  575. * @deprecated This method is inherently unsafe. See {@link #stop}
  576. * (with no arguments) for details. An additional danger of this
  577. * method is that it may be used to generate exceptions that the
  578. * target thread is unprepared to handle (including checked
  579. * exceptions that the thread could not possibly throw, were it
  580. * not for this method).
  581. * For more information, see
  582. * <a href="../../../guide/misc/threadPrimitiveDeprecation.html">Why
  583. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  584. */
  585. public final synchronized void stop(Throwable obj) {
  586. SecurityManager security = System.getSecurityManager();
  587. if (security != null) {
  588. checkAccess();
  589. if ((this != Thread.currentThread()) ||
  590. (!(obj instanceof ThreadDeath))) {
  591. if (stopThreadPermission == null)
  592. stopThreadPermission = new RuntimePermission("stopThread");
  593. security.checkPermission(stopThreadPermission);
  594. }
  595. }
  596. resume(); // Wake up thread if it was suspended; no-op otherwise
  597. stop0(obj);
  598. }
  599. /**
  600. * Interrupts this thread.
  601. *
  602. * <p>
  603. * First the <code>checkAccess</code> method of this thread is called
  604. * with no arguments. This may result in throwing a
  605. * <code>SecurityException</code>.
  606. *
  607. * @exception SecurityException if the current thread cannot modify
  608. * this thread.
  609. */
  610. // Note that this method is not synchronized. Three reasons for this:
  611. // 1) It changes the API.
  612. // 2) It's another place where the system could hang.
  613. // 3) All we're doing is turning on a one-way bit. It doesn't matter
  614. // exactly when it's done WRT probes via the interrupted() method.
  615. public void interrupt() {
  616. checkAccess();
  617. interrupt0();
  618. }
  619. /**
  620. * Tests whether the current thread has been interrupted. The
  621. * <i>interrupted status</i> of the thread is cleared by this method. In
  622. * other words, if this method were to be called twice in succession, the
  623. * second call would return false (unless the current thread were
  624. * interrupted again, after the first call had cleared its interrupted
  625. * status and before the second call had examined it).
  626. *
  627. * @return <code>true</code> if the current thread has been interrupted;
  628. * <code>false</code> otherwise.
  629. * @see java.lang.Thread#isInterrupted()
  630. */
  631. public static boolean interrupted() {
  632. return currentThread().isInterrupted(true);
  633. }
  634. /**
  635. * Tests whether this thread has been interrupted. The <i>interrupted
  636. * status</i> of the thread is unaffected by this method.
  637. *
  638. * @return <code>true</code> if this thread has been interrupted;
  639. * <code>false</code> otherwise.
  640. * @see java.lang.Thread#interrupted()
  641. */
  642. public boolean isInterrupted() {
  643. return isInterrupted(false);
  644. }
  645. /**
  646. * Tests if some Thread has been interrupted. The interrupted state
  647. * is reset or not based on the value of ClearInterrupted that is
  648. * passed.
  649. */
  650. private native boolean isInterrupted(boolean ClearInterrupted);
  651. /**
  652. * Destroys this thread, without any cleanup. Any monitors it has
  653. * locked remain locked. (This method is not implemented.)
  654. */
  655. public void destroy() {
  656. throw new NoSuchMethodError();
  657. }
  658. /**
  659. * Tests if this thread is alive. A thread is alive if it has
  660. * been started and has not yet died.
  661. *
  662. * @return <code>true</code> if this thread is alive;
  663. * <code>false</code> otherwise.
  664. */
  665. public final native boolean isAlive();
  666. /**
  667. * Suspends this thread.
  668. * <p>
  669. * First, the <code>checkAccess</code> method of this thread is called
  670. * with no arguments. This may result in throwing a
  671. * <code>SecurityException </code>(in the current thread).
  672. * <p>
  673. * If the thread is alive, it is suspended and makes no further
  674. * progress unless and until it is resumed.
  675. *
  676. * @exception SecurityException if the current thread cannot modify
  677. * this thread.
  678. * @see #checkAccess
  679. * @deprecated This method has been deprecated, as it is
  680. * inherently deadlock-prone. If the target thread holds a lock on the
  681. * monitor protecting a critical system resource when it is suspended, no
  682. * thread can access this resource until the target thread is resumed. If
  683. * the thread that would resume the target thread attempts to lock this
  684. * monitor prior to calling <code>resume</code>, deadlock results. Such
  685. * deadlocks typically manifest themselves as "frozen" processes.
  686. * For more information, see
  687. * <a href="../../../guide/misc/threadPrimitiveDeprecation.html">Why
  688. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  689. */
  690. public final void suspend() {
  691. checkAccess();
  692. suspend0();
  693. }
  694. /**
  695. * Resumes a suspended thread.
  696. * <p>
  697. * First, the <code>checkAccess</code> method of this thread is called
  698. * with no arguments. This may result in throwing a
  699. * <code>SecurityException</code> (in the current thread).
  700. * <p>
  701. * If the thread is alive but suspended, it is resumed and is
  702. * permitted to make progress in its execution.
  703. *
  704. * @exception SecurityException if the current thread cannot modify this
  705. * thread.
  706. * @see #checkAccess
  707. * @see java.lang.Thread#suspend()
  708. * @deprecated This method exists solely for use with {@link #suspend},
  709. * which has been deprecated because it is deadlock-prone.
  710. * For more information, see
  711. * <a href="../../../guide/misc/threadPrimitiveDeprecation.html">Why
  712. * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
  713. */
  714. public final void resume() {
  715. checkAccess();
  716. resume0();
  717. }
  718. /**
  719. * Changes the priority of this thread.
  720. * <p>
  721. * First the <code>checkAccess</code> method of this thread is called
  722. * with no arguments. This may result in throwing a
  723. * <code>SecurityException</code>.
  724. * <p>
  725. * Otherwise, the priority of this thread is set to the smaller of
  726. * the specified <code>newPriority</code> and the maximum permitted
  727. * priority of the thread's thread group.
  728. *
  729. * @exception IllegalArgumentException If the priority is not in the
  730. * range <code>MIN_PRIORITY</code> to
  731. * <code>MAX_PRIORITY</code>.
  732. * @exception SecurityException if the current thread cannot modify
  733. * this thread.
  734. * @see java.lang.Thread#checkAccess()
  735. * @see java.lang.Thread#getPriority()
  736. * @see java.lang.Thread#getThreadGroup()
  737. * @see java.lang.Thread#MAX_PRIORITY
  738. * @see java.lang.Thread#MIN_PRIORITY
  739. * @see java.lang.ThreadGroup#getMaxPriority()
  740. */
  741. public final void setPriority(int newPriority) {
  742. checkAccess();
  743. if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
  744. throw new IllegalArgumentException();
  745. }
  746. if (newPriority > group.getMaxPriority()) {
  747. newPriority = group.getMaxPriority();
  748. }
  749. setPriority0(priority = newPriority);
  750. }
  751. /**
  752. * Returns this thread's priority.
  753. *
  754. * @return this thread's name.
  755. * @see java.lang.Thread#setPriority(int)
  756. */
  757. public final int getPriority() {
  758. return priority;
  759. }
  760. /**
  761. * Changes the name of this thread to be equal to the argument
  762. * <code>name</code>.
  763. * <p>
  764. * First the <code>checkAccess</code> method of this thread is called
  765. * with no arguments. This may result in throwing a
  766. * <code>SecurityException</code>.
  767. *
  768. * @param name the new name for this thread.
  769. * @exception SecurityException if the current thread cannot modify this
  770. * thread.
  771. * @see java.lang.Thread#checkAccess()
  772. * @see java.lang.Thread#getName()
  773. */
  774. public final void setName(String name) {
  775. checkAccess();
  776. this.name = name.toCharArray();
  777. }
  778. /**
  779. * Returns this thread's name.
  780. *
  781. * @return this thread's name.
  782. * @see java.lang.Thread#setName(java.lang.String)
  783. */
  784. public final String getName() {
  785. return String.valueOf(name);
  786. }
  787. /**
  788. * Returns the thread group to which this thread belongs.
  789. * This method returns null if this thread has died
  790. * (been stopped).
  791. *
  792. * @return this thread's thread group.
  793. */
  794. public final ThreadGroup getThreadGroup() {
  795. return group;
  796. }
  797. /**
  798. * Returns the current number of active threads in this thread's
  799. * thread group.
  800. *
  801. * @return the current number of threads in this thread's thread group.
  802. */
  803. public static int activeCount() {
  804. return currentThread().getThreadGroup().activeCount();
  805. }
  806. /**
  807. * Copies into the specified array every active thread in
  808. * this thread's thread group and its subgroups. This method simply
  809. * calls the <code>enumerate</code> method of this thread's thread
  810. * group with the array argument.
  811. * <p>
  812. * First, if there is a security manager, that <code>enumerate</code>
  813. * method calls the security
  814. * manager's <code>checkAccess</code> method
  815. * with the thread group as its argument. This may result
  816. * in throwing a <code>SecurityException</code>.
  817. *
  818. * @return the number of threads put into the array.
  819. *
  820. * @exception SecurityException if a security manager exists and its
  821. * <code>checkAccess</code> method doesn't allow the operation.
  822. * @see java.lang.ThreadGroup#enumerate(java.lang.Thread[])
  823. * @see java.lang.SecurityManager#checkAccess(java.lang.ThreadGroup)
  824. */
  825. public static int enumerate(Thread tarray[]) {
  826. return currentThread().getThreadGroup().enumerate(tarray);
  827. }
  828. /**
  829. * Counts the number of stack frames in this thread. The thread must
  830. * be suspended.
  831. *
  832. * @return the number of stack frames in this thread.
  833. * @exception IllegalThreadStateException if this thread is not
  834. * suspended.
  835. * @deprecated The definition of this call depends on {@link #suspend},
  836. * which is deprecated. Further, the results of this call
  837. * were never well-defined.
  838. */
  839. public native int countStackFrames();
  840. /**
  841. * Waits at most <code>millis</code> milliseconds for this thread to
  842. * die. A timeout of <code>0</code> means to wait forever.
  843. *
  844. * @param millis the time to wait in milliseconds.
  845. * @exception InterruptedException if another thread has interrupted
  846. * the current thread. The <i>interrupted status</i> of the
  847. * current thread is cleared when this exception is thrown.
  848. */
  849. public final synchronized void join(long millis)
  850. throws InterruptedException {
  851. long base = System.currentTimeMillis();
  852. long now = 0;
  853. if (millis < 0) {
  854. throw new IllegalArgumentException("timeout value is negative");
  855. }
  856. if (millis == 0) {
  857. while (isAlive()) {
  858. wait(0);
  859. }
  860. } else {
  861. while (isAlive()) {
  862. long delay = millis - now;
  863. if (delay <= 0) {
  864. break;
  865. }
  866. wait(delay);
  867. now = System.currentTimeMillis() - base;
  868. }
  869. }
  870. }
  871. /**
  872. * Waits at most <code>millis</code> milliseconds plus
  873. * <code>nanos</code> nanoseconds for this thread to die.
  874. *
  875. * @param millis the time to wait in milliseconds.
  876. * @param nanos 0-999999 additional nanoseconds to wait.
  877. * @exception IllegalArgumentException if the value of millis is negative
  878. * the value of nanos is not in the range 0-999999.
  879. * @exception InterruptedException if another thread has interrupted
  880. * the current thread. The <i>interrupted status</i> of the
  881. * current thread is cleared when this exception is thrown.
  882. */
  883. public final synchronized void join(long millis, int nanos)
  884. throws InterruptedException {
  885. if (millis < 0) {
  886. throw new IllegalArgumentException("timeout value is negative");
  887. }
  888. if (nanos < 0 || nanos > 999999) {
  889. throw new IllegalArgumentException(
  890. "nanosecond timeout value out of range");
  891. }
  892. if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  893. millis++;
  894. }
  895. join(millis);
  896. }
  897. /**
  898. * Waits for this thread to die.
  899. *
  900. * @exception InterruptedException if another thread has interrupted
  901. * the current thread. The <i>interrupted status</i> of the
  902. * current thread is cleared when this exception is thrown.
  903. */
  904. public final void join() throws InterruptedException {
  905. join(0);
  906. }
  907. /**
  908. * Prints a stack trace of the current thread. This method is used
  909. * only for debugging.
  910. *
  911. * @see java.lang.Throwable#printStackTrace()
  912. */
  913. public static void dumpStack() {
  914. new Exception("Stack trace").printStackTrace();
  915. }
  916. /**
  917. * Marks this thread as either a daemon thread or a user thread. The
  918. * Java Virtual Machine exits when the only threads running are all
  919. * daemon threads.
  920. * <p>
  921. * This method must be called before the thread is started.
  922. * <p>
  923. * This method first calls the <code>checkAccess</code> method
  924. * of this thread
  925. * with no arguments. This may result in throwing a
  926. * <code>SecurityException </code>(in the current thread).
  927. *
  928. * @param on if <code>true</code>, marks this thread as a
  929. * daemon thread.
  930. * @exception IllegalThreadStateException if this thread is active.
  931. * @exception SecurityException if the current thread cannot modify
  932. * this thread.
  933. * @see java.lang.Thread#isDaemon()
  934. * @see #checkAccess
  935. */
  936. public final void setDaemon(boolean on) {
  937. checkAccess();
  938. if (isAlive()) {
  939. throw new IllegalThreadStateException();
  940. }
  941. daemon = on;
  942. }
  943. /**
  944. * Tests if this thread is a daemon thread.
  945. *
  946. * @return <code>true</code> if this thread is a daemon thread;
  947. * <code>false</code> otherwise.
  948. * @see java.lang.Thread#setDaemon(boolean)
  949. */
  950. public final boolean isDaemon() {
  951. return daemon;
  952. }
  953. /**
  954. * Determines if the currently running thread has permission to
  955. * modify this thread.
  956. * <p>
  957. * If there is a security manager, its <code>checkAccess</code> method
  958. * is called with this thread as its argument. This may result in
  959. * throwing a <code>SecurityException</code>.
  960. * <p>
  961. * Note: This method was mistakenly non-final in JDK 1.1.
  962. * It has been made final in JDK 1.2.
  963. *
  964. * @exception SecurityException if the current thread is not allowed to
  965. * access this thread.
  966. * @see java.lang.SecurityManager#checkAccess(java.lang.Thread)
  967. */
  968. public final void checkAccess() {
  969. SecurityManager security = System.getSecurityManager();
  970. if (security != null) {
  971. security.checkAccess(this);
  972. }
  973. }
  974. /**
  975. * Returns a string representation of this thread, including the
  976. * thread's name, priority, and thread group.
  977. *
  978. * @return a string representation of this thread.
  979. */
  980. public String toString() {
  981. if (getThreadGroup() != null) {
  982. return "Thread[" + getName() + "," + getPriority() + "," +
  983. getThreadGroup().getName() + "]";
  984. } else {
  985. return "Thread[" + getName() + "," + getPriority() + "," +
  986. "" + "]";
  987. }
  988. }
  989. /**
  990. * Returns the context ClassLoader for this Thread. The context
  991. * ClassLoader is provided by the creator of the thread for use
  992. * by code running in this thread when loading classes and resources.
  993. * If not set, the default is the ClassLoader context of the parent
  994. * Thread. The context ClassLoader of the primordial thread is
  995. * typically set to the class loader used to load the application.
  996. *
  997. * <p>First, if there is a security manager, and the caller's class
  998. * loader is not null and the caller's class loader is not the same as or
  999. * an ancestor of the context class loader for the thread whose
  1000. * context class loader is being requested, then the security manager's
  1001. * <code>checkPermission</code>
  1002. * method is called with a
  1003. * <code>RuntimePermission("getClassLoader")</code> permission
  1004. * to see if it's ok to get the context ClassLoader..
  1005. *
  1006. * @return the context ClassLoader for this Thread
  1007. *
  1008. * @throws SecurityException
  1009. * if a security manager exists and its
  1010. * <code>checkPermission</code> method doesn't allow
  1011. * getting the context ClassLoader.
  1012. *
  1013. * @see SecurityManager#checkPermission
  1014. * @see java.lang.RuntimePermission
  1015. *
  1016. * @since JDK1.2
  1017. */
  1018. public ClassLoader getContextClassLoader() {
  1019. if (contextClassLoader == null)
  1020. return null;
  1021. SecurityManager sm = System.getSecurityManager();
  1022. if (sm != null) {
  1023. ClassLoader ccl = ClassLoader.getCallerClassLoader();
  1024. if (ccl != null && ccl != contextClassLoader &&
  1025. !contextClassLoader.isAncestor(ccl)) {
  1026. sm.checkPermission(ClassLoader.getGetClassLoaderPerm());
  1027. }
  1028. }
  1029. return contextClassLoader;
  1030. }
  1031. /**
  1032. * Sets the context ClassLoader for this Thread. The context
  1033. * ClassLoader can be set when a thread is created, and allows
  1034. * the creator of the thread to provide the appropriate class loader
  1035. * to code running in the thread when loading classes and resources.
  1036. *
  1037. * <p>First, if there is a security manager, its <code>checkPermission</code>
  1038. * method is called with a
  1039. * <code>RuntimePermission("setContextClassLoader")</code> permission
  1040. * to see if it's ok to set the context ClassLoader..
  1041. *
  1042. * @param cl the context ClassLoader for this Thread
  1043. *
  1044. * @exception SecurityException if the current thread cannot set the
  1045. * context ClassLoader.
  1046. *
  1047. * @see SecurityManager#checkPermission
  1048. * @see java.lang.RuntimePermission
  1049. *
  1050. * @since JDK1.2
  1051. */
  1052. public void setContextClassLoader(ClassLoader cl) {
  1053. SecurityManager sm = System.getSecurityManager();
  1054. if (sm != null) {
  1055. sm.checkPermission(new RuntimePermission("setContextClassLoader"));
  1056. }
  1057. contextClassLoader = cl;
  1058. }
  1059. /* Some private helper methods */
  1060. private native void setPriority0(int newPriority);
  1061. private native void stop0(Object o);
  1062. private native void suspend0();
  1063. private native void resume0();
  1064. private native void interrupt0();
  1065. }