Share via


20.20 The Class java.lang.Thread

A thread is a single sequential flow of control. Thread objects allow multithreaded Java programming; a single Java Virtual Machine can execute many threads in an interleaved or concurrent manner.

In the method descriptions that follow, it is very important to distinguish among "the current thread" (the thread executing the method), "this Thread" (the object for which the method was invoked), and "this thread" (the thread that is represented by the Thread object for which the method was invoked).

public class Thread implements Runnable {
 public final static int MIN_PRIORITY = 1;
 public final static int MAX_PRIORITY = 10;
 public final static int NORM_PRIORITY = 5;
 public Thread();
 public Thread(String name);
 public Thread(Runnable target);
 public Thread(Runnable target, String name);
 public Thread(ThreadGroup group, String name)
     throws SecurityException, IllegalThreadStateException;
 public Thread(ThreadGroup group, Runnable target)
     throws SecurityException, IllegalThreadStateException;
 public Thread(ThreadGroup group, Runnable target,
            String name)
        throws SecurityException, IllegalThreadStateException;
 public String toString();
 public void checkAccess();
 public void run();
 public void start()
     throws IllegalThreadStateException;
 public final void stop()
     throws SecurityException;
 public final void stop(Throwable o)
     throws SecurityException;
 public final void suspend()
     throws SecurityException;
 public final void resume()
     throws SecurityException;
 public void destroy();
 public final boolean isAlive();
 public void interrupt();
 public static boolean interrupted();
 public boolean isInterrupted();
 public final String getName();
 public final void setName(String name)
     throws SecurityException;
 public final ThreadGroup getThreadGroup();
 public final int getPriority();
 public final void setPriority(int newPriority)
     throws SecurityException, IllegalArgumentException;
 public final boolean isDaemon();
 public final void setDaemon(boolean on)
     throws SecurityException;
 public int countStackFrames();
 public final void join()
     throws InterruptedException;
 public final void join(long millis)
     throws InterruptedException;
 public final void join(long millis, int nanos)
     throws InterruptedException;
    public void interrupt();
    public boolean isInterrupted();
    public static boolean interrupted();
    public static Thread currentThread();
 public static int activeCount();                                                            // deprecated
 public static int enumerate(Thread tarray[]);                                                           // deprecated
 public static void dumpStack();
 public static void yield();
 public static void sleep(long millis)

        throws InterruptedException;
 public static void sleep(long millis, int nanos)

        throws InterruptedException;
}

When a new Thread object is created, the thread it represents is not yet active. It is activated when some other thread calls the start method (§20.20.14) of the Thread object. This causes the thread represented by the Thread object to invoke the run method (§20.20.13) of the Thread object. The newly activated thread then remains alive until it stops because one of five things occurs:

  • The initial invocation of the run method by the newly activated thread completes normally through a normal return from the run method.
  • The initial invocation of the run method by the newly activated thread completes abruptly because an exception was thrown.
  • The thread invokes the stop method (§20.20.15) of the Thread object (and the security manager (§20.17.11) approves execution of the stop operation).
  • Some other thread invokes the stop method of the Thread object (and the security manager (§20.17.11) approves execution of the stop operation).
  • Some thread invokes the exit method (§20.16.2) of class Runtime (and the security manager (§20.17.13) approves execution of the exit operation); this stops every thread being run by the Java Virtual Machine that is running the thread that invokes the exit method.

As a thread dies, the notifyAll method (§20.1.10) is invoked for the Thread object that represents it; this fact is important for the proper operation of the join methods (§20.20.28, §20.20.29, §20.20.30). A thread is also removed from its thread group as it dies. Once a thread has been stopped, it is no longer alive and it cannot be restarted.

A thread that is alive can be suspended and resumed. A suspended thread is considered to be alive, but it performs no work, makes no progress, executes no virtual machine instructions. Resumption restores a thread to the state of active execution. A thread is suspended when it or another thread calls the suspend method (§20.20.17) of the Thread object that represents it (and the security manager (§20.17.11) approves execution of the suspend operation). A thread is resumed when another thread calls the resume method (§20.20.18) of the Thread object that represents it (and the security manager (§20.17.11) approves execution of the resume operation).

Every thread has a priority. When there is competition for processing resources, threads with higher priority are generally executed in preference to threads with lower priority. Such preference is not, however, a guarantee that the highest priority thread will always be running, and thread priorities cannot be used to implement mutual exclusion. When code running in some thread creates a new Thread object, the newly created thread has its priority initially set equal to the priority of the creating thread. But the priority of a thread T may be changed at any time if some thread invokes the setPriority method of the Thread object that represents T (and the security manager (§20.17.11) approves execution of the setPriority operation).

Each thread may or may not be marked as a daemon. When code running in some thread creates a new Thread object, the newly created thread is a daemon thread if and only if the creating thread is a daemon. But the daemonhood of a thread T may be changed before it is activated if some other thread invokes the setDaemon method of the Thread object that represents T (and the security manager (§20.17.11) approves execution of the setDaemon operation).

When a Java Virtual Machine starts up, there is usually a single non-daemon thread, which typically begins by invoking the method main of some designated class. The Java Virtual Machine continues to execute threads according to the thread execution model until all threads that are not daemon threads have stopped.

There are two ways to create a new thread of execution. One is to declare some class to be a subclass of Thread; this subclass should override the run method of class Thread. An instance of the subclass can then be created and started. For example, consider code for a thread whose job is to compute primes larger than a stated value:

class PrimeThread extends Thread {

   long minPrime;

   PrimeThread(long minPrime) {
     this.minPrime = minPrime;
 }

   public void run() {
         // compute primes larger than minPrime
     ...
 }

}

The following code would then create a thread and start it running:

PrimeThread p = new PrimeThread(143);
p.start();

The other way to create a thread is to is to declare some class to implement the Runnable interface, which also requires that the class implement the run method. An instance of the class can then be created, used to create a Thread, and started. The same example in this other style looks like this:

class PrimeRun implements Runnable {

   long minPrime;

   PrimeRun(long minPrime) {
     this.minPrime = minPrime;
 }


    public void run() {
         // compute primes larger than minPrime
     ...
 }

}

The following code would then create a thread and start it running:

PrimeRun p = new PrimeRun(143);
new Thread(p).start();

Every thread has a name, which is a String, for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.

Every thread that has not yet been stopped belongs to a thread group (§20.21). A thread can always create a new thread in its own thread group. To create a thread in some other thread group requires the approval of the checkAccess method (§20.21.4) of that thread group, which forwards the decision to the security manager (§20.17.11).

20.20.1 public final static int MIN_PRIORITY = 1;

The constant value of this field is 1, the smallest allowed priority for a thread.

20.20.2 public final static int MAX_PRIORITY = 10;

The constant value of this field is 10, the largest allowed priority value for a thread.

20.20.3 public final static int NORM_PRIORITY = 5;

The constant value of this field is 5, the normal priority for a thread that is not a daemon.

20.20.4 public Thread()

This constructor initializes a newly created Thread object so that it has no separate run object, has a newly generated name, and belongs to the same thread group as the thread that is creating the new thread.

This constructor has exactly the same effect as the explicit constructor call this(null, null, gname)(§20.20.10), where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n, where n is an integer.

20.20.5 public Thread(String name)

This constructor initializes a newly created Thread object so that it has no separate run object, has the specified name as its name, and belongs to the same thread group as the thread that is creating the new thread.

This constructor has exactly the same effect as the explicit constructor call this(null,``null,``name)(§20.20.10).

20.20.6 public Thread(Runnable runObject)

This constructor initializes a newly created Thread object so that it has the given runObject as its separate run object, has a newly generated name, and belongs to the same thread group as the thread that is creating the new thread.

This constructor has exactly the same effect as the explicit constructor call this(null,``runObject,gname)(§20.20.10) where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n where n is an integer.

20.20.7 public Thread(Runnable runObject, String name)

This constructor initializes a newly created Thread object so that it has the given runObject as its separate run object, has the specified name as its name, and belongs to the same thread group as the thread that is creating the new thread.

This constructor has exactly the same effect as the explicit constructor call this(null,``runObject,``name)(§20.20.10).

20.20.8 public Thread(ThreadGroup group, String name)throws SecurityException, IllegalThreadStateException

First, if group is not null, the checkAccess method (§20.21.4) of that thread group is called with no arguments.

This constructor initializes a newly created Thread object so that it has no separate run object, has the specified name as its name, and belongs to the thread group referred to by group (but if group is null, then the new thread will belong to the same thread group as the thread that is creating the new thread).

If group is a ThreadGroup that has been destroyed by method destroy(§20.21.11), then an IllegalThreadStateException is thrown.

This constructor has exactly the same effect as the explicit constructor call Thread(group,``null,``name)(§20.20.10).

20.20.9 public Thread(ThreadGroup group, Runnable runObject)throws SecurityException, IllegalThreadStateException

First, if group is not null, the checkAccess method (§20.21.4) of that thread group is called with no arguments.

This constructor initializes a newly created Thread object so that it has the given runObject as its separate run object, has a newly generated name, and belongs to the thread group referred to by group (but if group is null, then the new thread will belong to the same thread group as the thread that is creating the new thread).

If group is a ThreadGroup that has been destroyed by method destroy(§20.21.11), then an IllegalThreadStateException is thrown.

This constructor has exactly the same effect as the explicit constructor call this(group,``runObject,gname)(§20.20.10) where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n where n is an integer.

20.20.10 public Thread(ThreadGroup group, Runnable target, String name)throws SecurityException, IllegalThreadStateException

First, if group is not null, the checkAccess method (§20.21.4) of that thread group is called with no arguments; this may result in a SecurityException being thrown.

This constructor initializes a newly created Thread object so that it has the given runObject as its separate run object, has the specified name as its name, and belongs to the thread group referred to by group (but if group is null, then the new thread will belong to the same thread group as the thread that is creating the new thread).

If group is a ThreadGroup that has been destroyed by method destroy(§20.21.11), then an IllegalThreadStateException is thrown.

The priority of the newly created thread is set equal to the priority of the creating thread-that is, the currently running thread. The method setPriority(§20.20.23) may be used to change the priority to a new value.

The newly created thread is initially marked as being a daemon thread if and only if the thread creating it is a daemon thread. The method setDaemon (§20.20.25) may be used to change whether or not a thread is a daemon.

20.20.11 public String toString()

The returned value is a concatenation of the following seven strings:

All literal characters mentioned above are from the ACSII subset of Unicode.

Overrides the toString method of Object(§20.1.3).

20.20.12 public void checkAccess() throws SecurityException

If there is a security manager, its checkAccess method (§20.17.11) is called with this Thread object as its argument. This may result in a SecurityException being thrown in the current thread,.

This method is called by methods stop of no arguments (§20.20.15), stop of one argument (§20.20.16), suspend(§20.20.17), resume(§20.20.18), setName(§20.20.20), setPriority(§20.20.23), and setDaemon(§20.20.25).

20.20.13 public void run()

The general contract of this method is that it should perform the intended action of the thread.

The run method of class Thread simply calls the run method of the separate run object, if there is one; otherwise, it does nothing.

20.20.14 public void start()throws IllegalThreadStateException

Invoking this method causes this thread to begin execution; this thread calls the run method of this Thread object. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the thread represented by this Thread object (which executes its run method).

20.20.15 public final void stop()throws SecurityException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

This thread is forced to complete abnormally whatever it was doing and to throw a ThreadDeath object as an exception. For this purpose, this thread is resumed if it had been suspended, and is awakened if it had been asleep.

It is permitted to stop a thread that has not yet been started. If the thread is eventually started, it will immediately terminate.

User code should not normally try to catch ThreadDeath unless some extraordinary cleanup operation is necessary (note that the process of throwing a ThreadDeath exception will cause finally clauses of try statements to be executed before the thread officially dies). If a catch clause does catch a ThreadDeath object, it is important to rethrow the object so that the thread will actually die. The top-level error handler that reacts to otherwise uncaught exceptions will not print a message or otherwise signal or notify the user if the uncaught exception is an instance of ThreadDeath.

20.20.16 public final void stop(Throwable thr)throws SecurityException, NullPointerException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If the argument thr is null, then a NullPointerException is thrown (in the current thread).

This thread is forced to complete abnormally whatever it was doing and to throw the Throwable object thr as an exception. For this purpose, this thread is resumed if it had been suspended, and is awakened if it had been asleep. This is an unusual action to take; normally, the stop method that takes no arguments (§20.20.15) should be used.

It is permitted to stop a thread that has not yet been started. If the thread is eventually started, it will immediately terminate.

20.20.17 public final void suspend()throws SecurityException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If this thread is alive (§20.20.26), it is suspended and makes no further progress unless and until it is resumed. It is permitted to suspend a thread that is already in a suspended state; it remains suspended. Suspensions are not tallied; even if a thread is suspended more than once, only one call to resume is required to resume it.

20.20.18 public final void resume()throws SecurityException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If this thread is alive (§20.20.26) but suspended, it is resumed and is permitted to make progress in its execution. It is permitted to resume a thread that has never been suspended or has already been resumed; it continues to make progress in its execution. Resumptions are not tallied; even if a thread is resumed more than once, only one call to suspend is required to suspend it.

20.20.19 public final String getName()

The current name of this Thread object is returned as a String.

20.20.20 public final void setName(String name)throws SecurityException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

The name of this Thread object is changed to be equal to the argument name.

20.20.21 public final ThreadGroup getThreadGroup()

If this thread is alive, this method returns a reference to the ThreadGroup object that represents the thread group to which this thread belongs. If this thread has died (has been stopped), this method returns null.

20.20.22 public final int getPriority()

The current priority of this Thread object is returned.

20.20.23 public final void setPriority(int newPriority)throws SecurityException, IllegalArgumentException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If the newPriority argument is less than MIN_PRIORITY(§20.20.1) or greater than MAX_PRIORITY(§20.20.2), then an IllegalArgumentException is thrown.

Otherwise, the priority of this Thread object is set to the smaller of the specified newPriority and the maximum permitted priority (§20.21.12) of the thread's thread group (§20.20.21).

20.20.24 public final boolean isDaemon()

The result is true if and only if this thread is marked as a daemon thread.

20.20.25 public final void setDaemon(boolean on)throws SecurityException, IllegalThreadStateException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If this thread is alive, an IllegalThreadStateException is thrown. Otherwise, this thread is marked as being a daemon thread if the argument is true, and as not being a daemon thread if the argument is false.

20.20.26 public final boolean isAlive()

The result is true if and only if this thread is alive (it has been started and has not yet died).

20.20.27 public int countStackFrames()

This method returns the number of Java Virtual Machine stack frames currently active for this thread.

20.20.28 public final void join() throws InterruptedException

This method causes the current thread to wait (using the wait method (§20.1.6) of class Object) until this thread is no longer alive.

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.

20.20.29 public final void join(long millis) throws InterruptedException

This method causes the current thread to wait (using the wait method (§20.1.7) of class Object) until either this thread is no longer alive or a certain amount of real time has elapsed, more or less.

The amount of real time, measured in milliseconds, is given by millis. If millis is zero, however, then real time is not taken into consideration and this method simply waits until this thread is no longer alive.

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.

20.20.30 public final void join(long millis, int nanos) throws InterruptedException

This method causes the current thread to wait (using the wait method (§20.1.8) of class Object) until either this thread is no longer alive or a certain amount of real time has elapsed, more or less.

The amount of real time, measured in nanoseconds, is given by:

1000000*millis+nanos

In all other respects, this method does the same thing as the method join of one argument (§20.20.29). In particular, join(0,``0) means the same thing as join(0).

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.

20.20.31 public void interrupt()

An interrupt request is posted for this thread. This thread does not necessarily react immediately to the interrupt, however. If this thread is waiting, it is awakened and it then throws an InterruptedException.

[This method is scheduled for introduction in Java version 1.1.]

20.20.32 public boolean isInterrupted()

The result is true if and only if an interrupt request has been posted for this thread.

[This method is scheduled for introduction in Java version 1.1.]

20.20.33 public static boolean interrupted()

The result is true if and only if an interrupt request has been posted for the current thread.

[This method is scheduled for introduction in Java version 1.1.]

20.20.34 public static Thread currentThread()

The Thread object that represents the current thread is returned.

20.20.35 public static int activeCount()

This method returns the number of active threads in the thread group to which the current thread belongs. This count includes threads in subgroups of that thread group. This is the same as the value of the expression:

Threads.currentThread().getThreadGroup().activeCount()

[This method is deprecated for use in new code after Java version 1.1 becomes available. Instead, an expression equivalent to:

Threads.currentThread().getThreadGroup().allThreadsCount()

should be used. See the method allThreadsCount of class ThreadGroup.]

20.20.36 public static int enumerate(Thread tarray[])

The active threads in the thread group to which the current thread belongs, including threads in subgroups of that thread group, are enumerated and their Thread objects are put into the array tarray. The number of threads actually put into the array is returned. Call this value n; then the threads have been put into elements 0 through n-1 of tarray. If the number of threads exceeds the length of tarray, then some of the threads, tarray.length of them, are chosen arbitrarily and used to fill the array tarray.

[This method is deprecated for use in new code after Java version 1.1 becomes available. Instead, an expression equivalent to:

Threads.currentThread().getThreadGroup().allThreads()

should be used. See the method allThreads of class ThreadGroup.]

20.20.37 public static void dumpStack()

This is a utility method that makes it easy to print a stack dump for the current thread. It is equivalent in effect to:

new Exception("Stack trace").printStackTrace()

See the printStackTrace method (§20.22.6) of class Throwable.

20.20.38 public static void yield()

This method causes the current thread to yield, allowing the thread scheduler to choose another runnable thread for execution.

20.20.39 public static void sleep(long millis)throws InterruptedException

This method causes the current thread to yield and not to be scheduled for further execution until a certain amount of real time has elapsed, more or less.

The amount of real time, measured in milliseconds, is given by millis.

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the sleep is ended and an InterruptedException is thrown.

20.20.40 public static void sleep(long millis, int nanos)throws InterruptedException

This method causes the current thread to yield and not to be scheduled for further execution until a certain amount of real time has elapsed, more or less.

The amount of real time, measured in nanoseconds, is given by:

1000000*millis+nanos

In all other respects, this method does the same thing as the method sleep of one argument (§20.20.39). In particular, sleep(0,``0) means the same thing as sleep(0).

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the sleep is ended and an InterruptedException is thrown.