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