KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > lang > Thread


1 /*
2  * @(#)Thread.java 1.156 06/03/22
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.lang;
9
10 import java.security.AccessController JavaDoc;
11 import java.security.AccessControlContext JavaDoc;
12 import java.security.PrivilegedAction JavaDoc;
13 import java.util.Map JavaDoc;
14 import java.util.HashMap JavaDoc;
15 import java.util.Collections JavaDoc;
16 import java.util.concurrent.locks.LockSupport JavaDoc;
17 import sun.misc.SoftCache;
18 import sun.nio.ch.Interruptible;
19 import sun.security.util.SecurityConstants;
20
21
22 /**
23  * A <i>thread</i> is a thread of execution in a program. The Java
24  * Virtual Machine allows an application to have multiple threads of
25  * execution running concurrently.
26  * <p>
27  * Every thread has a priority. Threads with higher priority are
28  * executed in preference to threads with lower priority. Each thread
29  * may or may not also be marked as a daemon. When code running in
30  * some thread creates a new <code>Thread</code> object, the new
31  * thread has its priority initially set equal to the priority of the
32  * creating thread, and is a daemon thread if and only if the
33  * creating thread is a daemon.
34  * <p>
35  * When a Java Virtual Machine starts up, there is usually a single
36  * non-daemon thread (which typically calls the method named
37  * <code>main</code> of some designated class). The Java Virtual
38  * Machine continues to execute threads until either of the following
39  * occurs:
40  * <ul>
41  * <li>The <code>exit</code> method of class <code>Runtime</code> has been
42  * called and the security manager has permitted the exit operation
43  * to take place.
44  * <li>All threads that are not daemon threads have died, either by
45  * returning from the call to the <code>run</code> method or by
46  * throwing an exception that propagates beyond the <code>run</code>
47  * method.
48  * </ul>
49  * <p>
50  * There are two ways to create a new thread of execution. One is to
51  * declare a class to be a subclass of <code>Thread</code>. This
52  * subclass should override the <code>run</code> method of class
53  * <code>Thread</code>. An instance of the subclass can then be
54  * allocated and started. For example, a thread that computes primes
55  * larger than a stated value could be written as follows:
56  * <p><hr><blockquote><pre>
57  * class PrimeThread extends Thread {
58  * long minPrime;
59  * PrimeThread(long minPrime) {
60  * this.minPrime = minPrime;
61  * }
62  *
63  * public void run() {
64  * // compute primes larger than minPrime
65  * &nbsp;.&nbsp;.&nbsp;.
66  * }
67  * }
68  * </pre></blockquote><hr>
69  * <p>
70  * The following code would then create a thread and start it running:
71  * <p><blockquote><pre>
72  * PrimeThread p = new PrimeThread(143);
73  * p.start();
74  * </pre></blockquote>
75  * <p>
76  * The other way to create a thread is to declare a class that
77  * implements the <code>Runnable</code> interface. That class then
78  * implements the <code>run</code> method. An instance of the class can
79  * then be allocated, passed as an argument when creating
80  * <code>Thread</code>, and started. The same example in this other
81  * style looks like the following:
82  * <p><hr><blockquote><pre>
83  * class PrimeRun implements Runnable {
84  * long minPrime;
85  * PrimeRun(long minPrime) {
86  * this.minPrime = minPrime;
87  * }
88  *
89  * public void run() {
90  * // compute primes larger than minPrime
91  * &nbsp;.&nbsp;.&nbsp;.
92  * }
93  * }
94  * </pre></blockquote><hr>
95  * <p>
96  * The following code would then create a thread and start it running:
97  * <p><blockquote><pre>
98  * PrimeRun p = new PrimeRun(143);
99  * new Thread(p).start();
100  * </pre></blockquote>
101  * <p>
102  * Every thread has a name for identification purposes. More than
103  * one thread may have the same name. If a name is not specified when
104  * a thread is created, a new name is generated for it.
105  *
106  * @author unascribed
107  * @version 1.156, 03/22/06
108  * @see java.lang.Runnable
109  * @see java.lang.Runtime#exit(int)
110  * @see java.lang.Thread#run()
111  * @see java.lang.Thread#stop()
112  * @since JDK1.0
113  */

114 public
115 class Thread implements Runnable JavaDoc {
116     /* Make sure registerNatives is the first thing <clinit> does. */
117     private static native void registerNatives();
118     static {
119         registerNatives();
120     }
121
122     private char name[];
123     private int priority;
124     private Thread JavaDoc threadQ;
125     private long eetop;
126     private boolean started; // true iff this thread has been started
127

128     /* Whether or not to single_step this thread. */
129     private boolean single_step;
130
131     /* Whether or not the thread is a daemon thread. */
132     private boolean daemon = false;
133
134     /* Whether or not this thread was asked to exit before it runs.*/
135     private boolean stillborn = false;
136
137     /* What will be run. */
138     private Runnable JavaDoc target;
139
140     /* The group of this thread */
141     private ThreadGroup JavaDoc group;
142
143     /* The context ClassLoader for this thread */
144     private ClassLoader JavaDoc contextClassLoader;
145
146     /* The inherited AccessControlContext of this thread */
147     private AccessControlContext JavaDoc inheritedAccessControlContext;
148
149     /* For autonumbering anonymous threads. */
150     private static int threadInitNumber;
151     private static synchronized int nextThreadNum() {
152     return threadInitNumber++;
153     }
154
155     /* ThreadLocal values pertaining to this thread. This map is maintained
156      * by the ThreadLocal class. */

157     ThreadLocal.ThreadLocalMap JavaDoc threadLocals = null;
158
159     /*
160      * InheritableThreadLocal values pertaining to this thread. This map is
161      * maintained by the InheritableThreadLocal class.
162      */

163     ThreadLocal.ThreadLocalMap JavaDoc inheritableThreadLocals = null;
164
165     /*
166      * The requested stack size for this thread, or 0 if the creator did
167      * not specify a stack size. It is up to the VM to do whatever it
168      * likes with this number; some VMs will ignore it.
169      */

170     private long stackSize;
171
172     /*
173      * Thread ID
174      */

175     private long tid;
176
177     /* For generating thread ID */
178     private static long threadSeqNumber;
179
180     /* Java thread status for tools,
181      * initialized to indicate thread 'not yet started'
182      */

183     private int threadStatus = 0;
184
185
186     private static synchronized long nextThreadID() {
187     return ++threadSeqNumber;
188     }
189
190     /* The object in which this thread is blocked in an interruptible I/O
191      * operation, if any. The blocker's interrupt method should be invoked
192      * after setting this thread's interrupt status.
193      */

194     private volatile Interruptible blocker;
195     private Object JavaDoc blockerLock = new Object JavaDoc();
196
197     /* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code
198      */

199     void blockedOn(Interruptible b) {
200     synchronized (blockerLock) {
201         blocker = b;
202     }
203     }
204
205     /**
206      * The minimum priority that a thread can have.
207      */

208     public final static int MIN_PRIORITY = 1;
209
210    /**
211      * The default priority that is assigned to a thread.
212      */

213     public final static int NORM_PRIORITY = 5;
214
215     /**
216      * The maximum priority that a thread can have.
217      */

218     public final static int MAX_PRIORITY = 10;
219
220     /**
221      * Returns a reference to the currently executing thread object.
222      *
223      * @return the currently executing thread.
224      */

225     public static native Thread JavaDoc currentThread();
226
227     /**
228      * Causes the currently executing thread object to temporarily pause
229      * and allow other threads to execute.
230      */

231     public static native void yield();
232
233     /**
234      * Causes the currently executing thread to sleep (temporarily cease
235      * execution) for the specified number of milliseconds. The thread
236      * does not lose ownership of any monitors.
237      *
238      * @param millis the length of time to sleep in milliseconds.
239      * @exception InterruptedException if another thread has interrupted
240      * the current thread. The <i>interrupted status</i> of the
241      * current thread is cleared when this exception is thrown.
242      * @see java.lang.Object#notify()
243      */

244     public static native void sleep(long millis) throws InterruptedException JavaDoc;
245
246     /**
247      * Causes the currently executing thread to sleep (cease execution)
248      * for the specified number of milliseconds plus the specified number
249      * of nanoseconds. The thread does not lose ownership of any monitors.
250      *
251      * @param millis the length of time to sleep in milliseconds.
252      * @param nanos 0-999999 additional nanoseconds to sleep.
253      * @exception IllegalArgumentException if the value of millis is
254      * negative or the value of nanos is not in the range
255      * 0-999999.
256      * @exception InterruptedException if another thread has interrupted
257      * the current thread. The <i>interrupted status</i> of the
258      * current thread is cleared when this exception is thrown.
259      * @see java.lang.Object#notify()
260      */

261     public static void sleep(long millis, int nanos)
262     throws InterruptedException JavaDoc {
263     if (millis < 0) {
264             throw new IllegalArgumentException JavaDoc("timeout value is negative");
265     }
266
267     if (nanos < 0 || nanos > 999999) {
268             throw new IllegalArgumentException JavaDoc(
269                 "nanosecond timeout value out of range");
270     }
271
272     if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
273         millis++;
274     }
275
276     sleep(millis);
277     }
278
279     /**
280      * Initialize a Thread.
281      *
282      * @param g the Thread group
283      * @param target the object whose run() method gets called
284      * @param name the name of the new Thread
285      * @param stackSize the desired stack size for the new thread, or
286      * zero to indicate that this parameter is to be ignored.
287      */

288     private void init(ThreadGroup JavaDoc g, Runnable JavaDoc target, String JavaDoc name,
289                       long stackSize) {
290     Thread JavaDoc parent = currentThread();
291     SecurityManager JavaDoc security = System.getSecurityManager();
292     if (g == null) {
293         /* Determine if it's an applet or not */
294         
295         /* If there is a security manager, ask the security manager
296            what to do. */

297         if (security != null) {
298         g = security.getThreadGroup();
299         }
300
301         /* If the security doesn't have a strong opinion of the matter
302            use the parent thread group. */

303         if (g == null) {
304         g = parent.getThreadGroup();
305         }
306     }
307
308     /* checkAccess regardless of whether or not threadgroup is
309            explicitly passed in. */

310     g.checkAccess();
311
312     /*
313      * Do we have the required permissions?
314      */

315     if (security != null) {
316         if (isCCLOverridden(getClass())) {
317             security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
318         }
319     }
320
321
322         g.addUnstarted();
323
324     this.group = g;
325     this.daemon = parent.isDaemon();
326     this.priority = parent.getPriority();
327     this.name = name.toCharArray();
328     if (security == null || isCCLOverridden(parent.getClass()))
329         this.contextClassLoader = parent.getContextClassLoader();
330     else
331         this.contextClassLoader = parent.contextClassLoader;
332     this.inheritedAccessControlContext = AccessController.getContext();
333     this.target = target;
334     setPriority(priority);
335         if (parent.inheritableThreadLocals != null)
336         this.inheritableThreadLocals =
337         ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
338         /* Stash the specified stack size in case the VM cares */
339         this.stackSize = stackSize;
340
341         /* Set thread ID */
342         tid = nextThreadID();
343     }
344
345    /**
346      * Allocates a new <code>Thread</code> object. This constructor has
347      * the same effect as <code>Thread(null, null,</code>
348      * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
349      * a newly generated name. Automatically generated names are of the
350      * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
351      *
352      * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
353      * java.lang.Runnable, java.lang.String)
354      */

355     public Thread() {
356     init(null, null, "Thread-" + nextThreadNum(), 0);
357     }
358
359     /**
360      * Allocates a new <code>Thread</code> object. This constructor has
361      * the same effect as <code>Thread(null, target,</code>
362      * <i>gname</i><code>)</code>, where <i>gname</i> is
363      * a newly generated name. Automatically generated names are of the
364      * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
365      *
366      * @param target the object whose <code>run</code> method is called.
367      * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
368      * java.lang.Runnable, java.lang.String)
369      */

370     public Thread(Runnable JavaDoc target) {
371     init(null, target, "Thread-" + nextThreadNum(), 0);
372     }
373
374     /**
375      * Allocates a new <code>Thread</code> object. This constructor has
376      * the same effect as <code>Thread(group, target,</code>
377      * <i>gname</i><code>)</code>, where <i>gname</i> is
378      * a newly generated name. Automatically generated names are of the
379      * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
380      *
381      * @param group the thread group.
382      * @param target the object whose <code>run</code> method is called.
383      * @exception SecurityException if the current thread cannot create a
384      * thread in the specified thread group.
385      * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
386      * java.lang.Runnable, java.lang.String)
387      */

388     public Thread(ThreadGroup JavaDoc group, Runnable JavaDoc target) {
389     init(group, target, "Thread-" + nextThreadNum(), 0);
390     }
391
392     /**
393      * Allocates a new <code>Thread</code> object. This constructor has
394      * the same effect as <code>Thread(null, null, name)</code>.
395      *
396      * @param name the name of the new thread.
397      * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
398      * java.lang.Runnable, java.lang.String)
399      */

400     public Thread(String JavaDoc name) {
401     init(null, null, name, 0);
402     }
403
404     /**
405      * Allocates a new <code>Thread</code> object. This constructor has
406      * the same effect as <code>Thread(group, null, name)</code>
407      *
408      * @param group the thread group.
409      * @param name the name of the new thread.
410      * @exception SecurityException if the current thread cannot create a
411      * thread in the specified thread group.
412      * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
413      * java.lang.Runnable, java.lang.String)
414      */

415     public Thread(ThreadGroup JavaDoc group, String JavaDoc name) {
416     init(group, null, name, 0);
417     }
418
419     /**
420      * Allocates a new <code>Thread</code> object. This constructor has
421      * the same effect as <code>Thread(null, target, name)</code>.
422      *
423      * @param target the object whose <code>run</code> method is called.
424      * @param name the name of the new thread.
425      * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
426      * java.lang.Runnable, java.lang.String)
427      */

428     public Thread(Runnable JavaDoc target, String JavaDoc name) {
429     init(null, target, name, 0);
430     }
431
432     /**
433      * Allocates a new <code>Thread</code> object so that it has
434      * <code>target</code> as its run object, has the specified
435      * <code>name</code> as its name, and belongs to the thread group
436      * referred to by <code>group</code>.
437      * <p>
438      * If <code>group</code> is <code>null</code> and there is a
439      * security manager, the group is determined by the security manager's
440      * <code>getThreadGroup</code> method. If <code>group</code> is
441      * <code>null</code> and there is not a security manager, or the
442      * security manager's <code>getThreadGroup</code> method returns
443      * <code>null</code>, the group is set to be the same ThreadGroup
444      * as the thread that is creating the new thread.
445      *
446      * <p>If there is a security manager, its <code>checkAccess</code>
447      * method is called with the ThreadGroup as its argument.
448      * <p>In addition, its <code>checkPermission</code>
449      * method is called with the
450      * <code>RuntimePermission("enableContextClassLoaderOverride")</code>
451      * permission when invoked directly or indirectly by the constructor
452      * of a subclass which overrides the <code>getContextClassLoader</code>
453      * or <code>setContextClassLoader</code> methods.
454      * This may result in a SecurityException.
455
456      * <p>
457      * If the <code>target</code> argument is not <code>null</code>, the
458      * <code>run</code> method of the <code>target</code> is called when
459      * this thread is started. If the target argument is
460      * <code>null</code>, this thread's <code>run</code> method is called
461      * when this thread is started.
462      * <p>
463      * The priority of the newly created thread is set equal to the
464      * priority of the thread creating it, that is, the currently running
465      * thread. The method <code>setPriority</code> may be used to
466      * change the priority to a new value.
467      * <p>
468      * The newly created thread is initially marked as being a daemon
469      * thread if and only if the thread creating it is currently marked
470      * as a daemon thread. The method <code>setDaemon </code> may be used
471      * to change whether or not a thread is a daemon.
472      *
473      * @param group the thread group.
474      * @param target the object whose <code>run</code> method is called.
475      * @param name the name of the new thread.
476      * @exception SecurityException if the current thread cannot create a
477      * thread in the specified thread group or cannot
478      * override the context class loader methods.
479      * @see java.lang.Runnable#run()
480      * @see java.lang.Thread#run()
481      * @see java.lang.Thread#setDaemon(boolean)
482      * @see java.lang.Thread#setPriority(int)
483      * @see java.lang.ThreadGroup#checkAccess()
484      * @see SecurityManager#checkAccess
485      */

486     public Thread(ThreadGroup JavaDoc group, Runnable JavaDoc target, String JavaDoc name) {
487     init(group, target, name, 0);
488     }
489
490     /**
491      * Allocates a new <code>Thread</code> object so that it has
492      * <code>target</code> as its run object, has the specified
493      * <code>name</code> as its name, belongs to the thread group referred to
494      * by <code>group</code>, and has the specified <i>stack size</i>.
495      *
496      * <p>This constructor is identical to {@link
497      * #Thread(ThreadGroup,Runnable,String)} with the exception of the fact
498      * that it allows the thread stack size to be specified. The stack size
499      * is the approximate number of bytes of address space that the virtual
500      * machine is to allocate for this thread's stack. <b>The effect of the
501      * <tt>stackSize</tt> parameter, if any, is highly platform dependent.</b>
502      *
503      * <p>On some platforms, specifying a higher value for the
504      * <tt>stackSize</tt> parameter may allow a thread to achieve greater
505      * recursion depth before throwing a {@link StackOverflowError}.
506      * Similarly, specifying a lower value may allow a greater number of
507      * threads to exist concurrently without throwing an {@link
508      * OutOfMemoryError} (or other internal error). The details of
509      * the relationship between the value of the <tt>stackSize</tt> parameter
510      * and the maximum recursion depth and concurrency level are
511      * platform-dependent. <b>On some platforms, the value of the
512      * <tt>stackSize</tt> parameter may have no effect whatsoever.</b>
513      *
514      * <p>The virtual machine is free to treat the <tt>stackSize</tt>
515      * parameter as a suggestion. If the specified value is unreasonably low
516      * for the platform, the virtual machine may instead use some
517      * platform-specific minimum value; if the specified value is unreasonably
518      * high, the virtual machine may instead use some platform-specific
519      * maximum. Likewise, the virtual machine is free to round the specified
520      * value up or down as it sees fit (or to ignore it completely).
521      *
522      * <p>Specifying a value of zero for the <tt>stackSize</tt> parameter will
523      * cause this constructor to behave exactly like the
524      * <tt>Thread(ThreadGroup, Runnable, String)</tt> constructor.
525      *
526      * <p><i>Due to the platform-dependent nature of the behavior of this
527      * constructor, extreme care should be exercised in its use.
528      * The thread stack size necessary to perform a given computation will
529      * likely vary from one JRE implementation to another. In light of this
530      * variation, careful tuning of the stack size parameter may be required,
531      * and the tuning may need to be repeated for each JRE implementation on
532      * which an application is to run.</i>
533      *
534      * <p>Implementation note: Java platform implementers are encouraged to
535      * document their implementation's behavior with respect to the
536      * <tt>stackSize parameter</tt>.
537      *
538      * @param group the thread group.
539      * @param target the object whose <code>run</code> method is called.
540      * @param name the name of the new thread.
541      * @param stackSize the desired stack size for the new thread, or
542      * zero to indicate that this parameter is to be ignored.
543      * @exception SecurityException if the current thread cannot create a
544      * thread in the specified thread group.
545      */

546     public Thread(ThreadGroup JavaDoc group, Runnable JavaDoc target, String JavaDoc name,
547                   long stackSize) {
548     init(group, target, name, stackSize);
549     }
550
551     /**
552      * Causes this thread to begin execution; the Java Virtual Machine
553      * calls the <code>run</code> method of this thread.
554      * <p>
555      * The result is that two threads are running concurrently: the
556      * current thread (which returns from the call to the
557      * <code>start</code> method) and the other thread (which executes its
558      * <code>run</code> method).
559      * <p>
560      * It is never legal to start a thread more than once.
561      * In particular, a thread may not be restarted once it has completed
562      * execution.
563      *
564      * @exception IllegalThreadStateException if the thread was already
565      * started.
566      * @see java.lang.Thread#run()
567      * @see java.lang.Thread#stop()
568      */

569     public synchronized void start() {
570         if (started)
571             throw new IllegalThreadStateException JavaDoc();
572         started = true;
573         group.add(this);
574         start0();
575     }
576
577     private native void start0();
578
579     /**
580      * If this thread was constructed using a separate
581      * <code>Runnable</code> run object, then that
582      * <code>Runnable</code> object's <code>run</code> method is called;
583      * otherwise, this method does nothing and returns.
584      * <p>
585      * Subclasses of <code>Thread</code> should override this method.
586      *
587      * @see java.lang.Thread#start()
588      * @see java.lang.Thread#stop()
589      * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
590      * java.lang.Runnable, java.lang.String)
591      * @see java.lang.Runnable#run()
592      */

593     public void run() {
594     if (target != null) {
595         target.run();
596     }
597     }
598
599     /**
600      * This method is called by the system to give a Thread
601      * a chance to clean up before it actually exits.
602      */

603     private void exit() {
604     if (group != null) {
605         group.remove(this);
606         group = null;
607     }
608     /* Aggressively null out all reference fields: see bug 4006245 */
609     target = null;
610     /* Speed the release of some of these resources */
611         threadLocals = null;
612         inheritableThreadLocals = null;
613         inheritedAccessControlContext = null;
614         blocker = null;
615         uncaughtExceptionHandler = null;
616     }
617
618     /**
619      * Forces the thread to stop executing.
620      * <p>
621      * If there is a security manager installed, its <code>checkAccess</code>
622      * method is called with <code>this</code>
623      * as its argument. This may result in a
624      * <code>SecurityException</code> being raised (in the current thread).
625      * <p>
626      * If this thread is different from the current thread (that is, the current
627      * thread is trying to stop a thread other than itself), the
628      * security manager's <code>checkPermission</code> method (with a
629      * <code>RuntimePermission("stopThread")</code> argument) is called in
630      * addition.
631      * Again, this may result in throwing a
632      * <code>SecurityException</code> (in the current thread).
633      * <p>
634      * The thread represented by this thread is forced to stop whatever
635      * it is doing abnormally and to throw a newly created
636      * <code>ThreadDeath</code> object as an exception.
637      * <p>
638      * It is permitted to stop a thread that has not yet been started.
639      * If the thread is eventually started, it immediately terminates.
640      * <p>
641      * An application should not normally try to catch
642      * <code>ThreadDeath</code> unless it must do some extraordinary
643      * cleanup operation (note that the throwing of
644      * <code>ThreadDeath</code> causes <code>finally</code> clauses of
645      * <code>try</code> statements to be executed before the thread
646      * officially dies). If a <code>catch</code> clause catches a
647      * <code>ThreadDeath</code> object, it is important to rethrow the
648      * object so that the thread actually dies.
649      * <p>
650      * The top-level error handler that reacts to otherwise uncaught
651      * exceptions does not print out a message or otherwise notify the
652      * application if the uncaught exception is an instance of
653      * <code>ThreadDeath</code>.
654      *
655      * @exception SecurityException if the current thread cannot
656      * modify this thread.
657      * @see java.lang.Thread#interrupt()
658      * @see java.lang.Thread#checkAccess()
659      * @see java.lang.Thread#run()
660      * @see java.lang.Thread#start()
661      * @see java.lang.ThreadDeath
662      * @see java.lang.ThreadGroup#uncaughtException(java.lang.Thread,
663      * java.lang.Throwable)
664      * @see SecurityManager#checkAccess(Thread)
665      * @see SecurityManager#checkPermission
666      * @deprecated This method is inherently unsafe. Stopping a thread with
667      * Thread.stop causes it to unlock all of the monitors that it
668      * has locked (as a natural consequence of the unchecked
669      * <code>ThreadDeath</code> exception propagating up the stack). If
670      * any of the objects previously protected by these monitors were in
671      * an inconsistent state, the damaged objects become visible to
672      * other threads, potentially resulting in arbitrary behavior. Many
673      * uses of <code>stop</code> should be replaced by code that simply
674      * modifies some variable to indicate that the target thread should
675      * stop running. The target thread should check this variable
676      * regularly, and return from its run method in an orderly fashion
677      * if the variable indicates that it is to stop running. If the
678      * target thread waits for long periods (on a condition variable,
679      * for example), the <code>interrupt</code> method should be used to
680      * interrupt the wait.
681      * For more information, see
682      * <a HREF="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
683      * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
684      */

685     @Deprecated JavaDoc
686     public final void stop() {
687     synchronized (this) {
688             //if the thread is already dead, return
689
if (!this.isAlive()) return;
690         SecurityManager JavaDoc security = System.getSecurityManager();
691         if (security != null) {
692         checkAccess();
693         if (this != Thread.currentThread()) {
694             security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
695         }
696         }
697         resume(); // Wake up thread if it was suspended; no-op otherwise
698
stop0(new ThreadDeath JavaDoc());
699     }
700     }
701
702     /**
703      * Forces the thread to stop executing.
704      * <p>
705      * If there is a security manager installed, the <code>checkAccess</code>
706      * method of this thread is called, which may result in a
707      * <code>SecurityException</code> being raised (in the current thread).
708      * <p>
709      * If this thread is different from the current thread (that is, the current
710      * thread is trying to stop a thread other than itself) or
711      * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
712      * security manager's <code>checkPermission</code> method (with the
713      * <code>RuntimePermission("stopThread")</code> argument) is called in
714      * addition.
715      * Again, this may result in throwing a
716      * <code>SecurityException</code> (in the current thread).
717      * <p>
718      * If the argument <code>obj</code> is null, a
719      * <code>NullPointerException</code> is thrown (in the current thread).
720      * <p>
721      * The thread represented by this thread is forced to complete
722      * whatever it is doing abnormally and to throw the
723      * <code>Throwable</code> object <code>obj</code> as an exception. This
724      * is an unusual action to take; normally, the <code>stop</code> method
725      * that takes no arguments should be used.
726      * <p>
727      * It is permitted to stop a thread that has not yet been started.
728      * If the thread is eventually started, it immediately terminates.
729      *
730      * @param obj the Throwable object to be thrown.
731      * @exception SecurityException if the current thread cannot modify
732      * this thread.
733      * @see java.lang.Thread#interrupt()
734      * @see java.lang.Thread#checkAccess()
735      * @see java.lang.Thread#run()
736      * @see java.lang.Thread#start()
737      * @see java.lang.Thread#stop()
738      * @see SecurityManager#checkAccess(Thread)
739      * @see SecurityManager#checkPermission
740      * @deprecated This method is inherently unsafe. See {@link #stop()}
741      * for details. An additional danger of this
742      * method is that it may be used to generate exceptions that the
743      * target thread is unprepared to handle (including checked
744      * exceptions that the thread could not possibly throw, were it
745      * not for this method).
746      * For more information, see
747      * <a HREF="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
748      * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
749      */

750     @Deprecated JavaDoc
751     public final synchronized void stop(Throwable JavaDoc obj) {
752     SecurityManager JavaDoc security = System.getSecurityManager();
753     if (security != null) {
754         checkAccess();
755         if ((this != Thread.currentThread()) ||
756         (!(obj instanceof ThreadDeath JavaDoc))) {
757         security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
758         }
759     }
760     resume(); // Wake up thread if it was suspended; no-op otherwise
761
stop0(obj);
762     }
763
764     /**
765      * Interrupts this thread.
766      *
767      * <p> Unless the current thread is interrupting itself, which is
768      * always permitted, the {@link #checkAccess() checkAccess} method
769      * of this thread is invoked, which may cause a {@link
770      * SecurityException} to be thrown.
771      *
772      * <p> If this thread is blocked in an invocation of the {@link
773      * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
774      * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
775      * class, or of the {@link #join()}, {@link #join(long)}, {@link
776      * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
777      * methods of this class, then its interrupt status will be cleared and it
778      * will receive an {@link InterruptedException}.
779      *
780      * <p> If this thread is blocked in an I/O operation upon an {@link
781      * java.nio.channels.InterruptibleChannel </code>interruptible
782      * channel<code>} then the channel will be closed, the thread's interrupt
783      * status will be set, and the thread will receive a {@link
784      * java.nio.channels.ClosedByInterruptException}.
785      *
786      * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
787      * then the thread's interrupt status will be set and it will return
788      * immediately from the selection operation, possibly with a non-zero
789      * value, just as if the selector's {@link
790      * java.nio.channels.Selector#wakeup wakeup} method were invoked.
791      *
792      * <p> If none of the previous conditions hold then this thread's interrupt
793      * status will be set. </p>
794      *
795      * @throws SecurityException
796      * if the current thread cannot modify this thread
797      *
798      * @revised 1.4
799      * @spec JSR-51
800      */

801     public void interrupt() {
802     if (this != Thread.currentThread())
803         checkAccess();
804
805     synchronized (blockerLock) {
806         Interruptible b = blocker;
807         if (b != null) {
808         interrupt0(); // Just to set the interrupt flag
809
b.interrupt();
810         return;
811         }
812     }
813     interrupt0();
814     }
815
816     /**
817      * Tests whether the current thread has been interrupted. The
818      * <i>interrupted status</i> of the thread is cleared by this method. In
819      * other words, if this method were to be called twice in succession, the
820      * second call would return false (unless the current thread were
821      * interrupted again, after the first call had cleared its interrupted
822      * status and before the second call had examined it).
823      *
824      * @return <code>true</code> if the current thread has been interrupted;
825      * <code>false</code> otherwise.
826      * @see java.lang.Thread#isInterrupted()
827      */

828     public static boolean interrupted() {
829     return currentThread().isInterrupted(true);
830     }
831
832     /**
833      * Tests whether this thread has been interrupted. The <i>interrupted
834      * status</i> of the thread is unaffected by this method.
835      *
836      * @return <code>true</code> if this thread has been interrupted;
837      * <code>false</code> otherwise.
838      * @see java.lang.Thread#interrupted()
839      */

840     public boolean isInterrupted() {
841     return isInterrupted(false);
842     }
843
844     /**
845      * Tests if some Thread has been interrupted. The interrupted state
846      * is reset or not based on the value of ClearInterrupted that is
847      * passed.
848      */

849     private native boolean isInterrupted(boolean ClearInterrupted);
850
851     /**
852      * Throws {@link NoSuchMethodError}.
853      *
854      * @deprecated This method was originally designed to destroy this
855      * thread without any cleanup. Any monitors it held would have
856      * remained locked. However, the method was never implemented.
857      * If if were to be implemented, it would be deadlock-prone in
858      * much the manner of {@link #suspend}. If the target thread held
859      * a lock protecting a critical system resource when it was
860      * destroyed, no thread could ever access this resource again.
861      * If another thread ever attempted to lock this resource, deadlock
862      * would result. Such deadlocks typically manifest themselves as
863      * "frozen" processes. For more information, see
864      * <a HREF="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">
865      * Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
866      * @throws NoSuchMethodError always
867      */

868     @Deprecated JavaDoc
869     public void destroy() {
870     throw new NoSuchMethodError JavaDoc();
871     }
872
873     /**
874      * Tests if this thread is alive. A thread is alive if it has
875      * been started and has not yet died.
876      *
877      * @return <code>true</code> if this thread is alive;
878      * <code>false</code> otherwise.
879      */

880     public final native boolean isAlive();
881
882     /**
883      * Suspends this thread.
884      * <p>
885      * First, the <code>checkAccess</code> method of this thread is called
886      * with no arguments. This may result in throwing a
887      * <code>SecurityException </code>(in the current thread).
888      * <p>
889      * If the thread is alive, it is suspended and makes no further
890      * progress unless and until it is resumed.
891      *
892      * @exception SecurityException if the current thread cannot modify
893      * this thread.
894      * @see #checkAccess
895      * @deprecated This method has been deprecated, as it is
896      * inherently deadlock-prone. If the target thread holds a lock on the
897      * monitor protecting a critical system resource when it is suspended, no
898      * thread can access this resource until the target thread is resumed. If
899      * the thread that would resume the target thread attempts to lock this
900      * monitor prior to calling <code>resume</code>, deadlock results. Such
901      * deadlocks typically manifest themselves as "frozen" processes.
902      * For more information, see
903      * <a HREF="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
904      * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
905      */

906     @Deprecated JavaDoc
907     public final void suspend() {
908     checkAccess();
909     suspend0();
910     }
911
912     /**
913      * Resumes a suspended thread.
914      * <p>
915      * First, the <code>checkAccess</code> method of this thread is called
916      * with no arguments. This may result in throwing a
917      * <code>SecurityException</code> (in the current thread).
918      * <p>
919      * If the thread is alive but suspended, it is resumed and is
920      * permitted to make progress in its execution.
921      *
922      * @exception SecurityException if the current thread cannot modify this
923      * thread.
924      * @see #checkAccess
925      * @see java.lang.Thread#suspend()
926      * @deprecated This method exists solely for use with {@link #suspend},
927      * which has been deprecated because it is deadlock-prone.
928      * For more information, see
929      * <a HREF="{@docRoot}/../guide/misc/threadPrimitiveDeprecation.html">Why
930      * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
931      */

932     @Deprecated JavaDoc
933     public final void resume() {
934     checkAccess();
935     resume0();
936     }
937
938     /**
939      * Changes the priority of this thread.
940      * <p>
941      * First the <code>checkAccess</code> method of this thread is called
942      * with no arguments. This may result in throwing a
943      * <code>SecurityException</code>.
944      * <p>
945      * Otherwise, the priority of this thread is set to the smaller of
946      * the specified <code>newPriority</code> and the maximum permitted
947      * priority of the thread's thread group.
948      *
949      * @param newPriority priority to set this thread to
950      * @exception IllegalArgumentException If the priority is not in the
951      * range <code>MIN_PRIORITY</code> to
952      * <code>MAX_PRIORITY</code>.
953      * @exception SecurityException if the current thread cannot modify
954      * this thread.
955      * @see #getPriority
956      * @see java.lang.Thread#checkAccess()
957      * @see java.lang.Thread#getPriority()
958      * @see java.lang.Thread#getThreadGroup()
959      * @see java.lang.Thread#MAX_PRIORITY
960      * @see java.lang.Thread#MIN_PRIORITY
961      * @see java.lang.ThreadGroup#getMaxPriority()
962      */

963     public final void setPriority(int newPriority) {
964     checkAccess();
965     if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
966         throw new IllegalArgumentException JavaDoc();
967     }
968     if (newPriority > group.getMaxPriority()) {
969         newPriority = group.getMaxPriority();
970     }
971     setPriority0(priority = newPriority);
972     }
973
974     /**
975      * Returns this thread's priority.
976      *
977      * @return this thread's priority.
978      * @see #setPriority
979      * @see java.lang.Thread#setPriority(int)
980      */

981     public final int getPriority() {
982     return priority;
983     }
984
985     /**
986      * Changes the name of this thread to be equal to the argument
987      * <code>name</code>.
988      * <p>
989      * First the <code>checkAccess</code> method of this thread is called
990      * with no arguments. This may result in throwing a
991      * <code>SecurityException</code>.
992      *
993      * @param name the new name for this thread.
994      * @exception SecurityException if the current thread cannot modify this
995      * thread.
996      * @see #getName
997      * @see java.lang.Thread#checkAccess()
998      * @see java.lang.Thread#getName()
999      */

1000    public