Skip to content

Most visited

Recently visited

navigation
Added in API level 1

Thread

public class Thread
extends Object implements Runnable

java.lang.Object
   ↳ java.lang.Thread
Known Direct Subclasses


A Thread is a concurrent unit of execution. It has its own call stack for methods being invoked, their arguments and local variables. Each application has at least one thread running when it is started, the main thread, in the main ThreadGroup. The runtime keeps its own threads in the system thread group.

There are two ways to execute code in a new thread. You can either subclass Thread and overriding its run() method, or construct a new Thread and pass a Runnable to the constructor. In either case, the start() method must be called to actually execute the new Thread.

Each Thread has an integer priority that affect how the thread is scheduled by the OS. A new thread inherits the priority of its parent. A thread's priority can be set using the setPriority(int) method.

Summary

Nested classes

enum Thread.State

A representation of a thread's state. 

interface Thread.UncaughtExceptionHandler

Implemented by objects that want to handle cases where a thread is being terminated by an uncaught exception. 

Constants

int MAX_PRIORITY

The maximum priority value allowed for a thread.

int MIN_PRIORITY

The minimum priority value allowed for a thread.

int NORM_PRIORITY

The normal (default) priority value assigned to the main thread.

Public constructors

Thread()

Constructs a new Thread with no Runnable object and a newly generated name.

Thread(Runnable runnable)

Constructs a new Thread with a Runnable object and a newly generated name.

Thread(Runnable runnable, String threadName)

Constructs a new Thread with a Runnable object and name provided.

Thread(String threadName)

Constructs a new Thread with no Runnable object and the name provided.

Thread(ThreadGroup group, Runnable runnable)

Constructs a new Thread with a Runnable object and a newly generated name.

Thread(ThreadGroup group, Runnable runnable, String threadName)

Constructs a new Thread with a Runnable object, the given name and belonging to the ThreadGroup passed as parameter.

Thread(ThreadGroup group, String threadName)

Constructs a new Thread with no Runnable object, the given name and belonging to the ThreadGroup passed as parameter.

Thread(ThreadGroup group, Runnable runnable, String threadName, long stackSize)

Constructs a new Thread with a Runnable object, the given name and belonging to the ThreadGroup passed as parameter.

Public methods

static int activeCount()

Returns the number of active Threads in the running Thread's group and its subgroups.

final void checkAccess()

Does nothing.

int countStackFrames()

This method was deprecated in API level 1. The results of this call were never well defined. To make things worse, it would depend on whether the Thread was suspended or not, and suspend was deprecated too.

static Thread currentThread()

Returns the Thread of the caller, that is, the current Thread.

void destroy()

This method was deprecated in API level 1. Not implemented.

static void dumpStack()

Prints to the standard error stream a text representation of the current stack for this Thread.

static int enumerate(Thread[] threads)

Copies an array with all Threads which are in the same ThreadGroup as the receiver - and subgroups - into the array threads passed as parameter.

static Map<ThreadStackTraceElement[]> getAllStackTraces()

Returns a map of all the currently live threads to their stack traces.

ClassLoader getContextClassLoader()

Returns the context ClassLoader for this Thread.

static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()

Returns the default exception handler that's executed when uncaught exception terminates a thread.

long getId()

Returns the thread's identifier.

final String getName()

Returns the name of the Thread.

final int getPriority()

Returns the priority of the Thread.

StackTraceElement[] getStackTrace()

Returns an array of StackTraceElement representing the current thread's stack.

Thread.State getState()

Returns the current state of the Thread.

final ThreadGroup getThreadGroup()

Returns the ThreadGroup to which this Thread belongs.

Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()

Returns the thread's uncaught exception handler.

static boolean holdsLock(Object object)

Indicates whether the current Thread has a monitor lock on the specified object.

void interrupt()

Posts an interrupt request to this Thread.

static boolean interrupted()

Returns a boolean indicating whether the current Thread ( currentThread()) has a pending interrupt request ( true) or not (false).

final boolean isAlive()

Returns true if the receiver has already been started and still runs code (hasn't died yet).

final boolean isDaemon()

Tests whether this is a daemon thread.

boolean isInterrupted()

Returns a boolean indicating whether the receiver has a pending interrupt request (true) or not ( false)

final void join()

Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies.

final void join(long millis, int nanos)

Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.

final void join(long millis)

Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.

final void resume()

This method was deprecated in API level 1. Only useful in conjunction with deprecated method suspend().

void run()

Calls the run() method of the Runnable object the receiver holds.

void setContextClassLoader(ClassLoader cl)

Set the context ClassLoader for the receiver.

final void setDaemon(boolean isDaemon)

Marks this thread as a daemon thread.

static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)

Sets the default uncaught exception handler.

final void setName(String threadName)

Sets the name of the Thread.

final void setPriority(int priority)

Sets the priority of this thread.

void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)

Sets the uncaught exception handler.

static void sleep(long millis, int nanos)

Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds and nanoseconds).

static void sleep(long time)

Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds).

void start()

Starts the new Thread of execution.

final void stop(Throwable throwable)

This method was deprecated in API level 1. because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.

final void stop()

This method was deprecated in API level 1. because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.

final void suspend()

This method was deprecated in API level 1. May cause deadlocks.

String toString()

Returns a string containing a concise, human-readable description of the Thread.

static void yield()

Causes the calling Thread to yield execution time to another Thread that is ready to run.

Inherited methods

From class java.lang.Object
From interface java.lang.Runnable

Constants

MAX_PRIORITY

Added in API level 1
int MAX_PRIORITY

The maximum priority value allowed for a thread. This corresponds to (but does not have the same value as) android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY.

Constant Value: 10 (0x0000000a)

MIN_PRIORITY

Added in API level 1
int MIN_PRIORITY

The minimum priority value allowed for a thread. This corresponds to (but does not have the same value as) android.os.Process.THREAD_PRIORITY_LOWEST.

Constant Value: 1 (0x00000001)

NORM_PRIORITY

Added in API level 1
int NORM_PRIORITY

The normal (default) priority value assigned to the main thread. This corresponds to (but does not have the same value as) android.os.Process.THREAD_PRIORITY_DEFAULT.

Constant Value: 5 (0x00000005)

Public constructors

Thread

Added in API level 1
Thread ()

Constructs a new Thread with no Runnable object and a newly generated name. The new Thread will belong to the same ThreadGroup as the Thread calling this constructor.

See also:

Thread

Added in API level 1
Thread (Runnable runnable)

Constructs a new Thread with a Runnable object and a newly generated name. The new Thread will belong to the same ThreadGroup as the Thread calling this constructor.

Parameters
runnable Runnable: a Runnable whose method run will be executed by the new Thread

See also:

Thread

Added in API level 1
Thread (Runnable runnable, 
                String threadName)

Constructs a new Thread with a Runnable object and name provided. The new Thread will belong to the same ThreadGroup as the Thread calling this constructor.

Parameters
runnable Runnable: a Runnable whose method run will be executed by the new Thread
threadName String: the name for the Thread being created

See also:

Thread

Added in API level 1
Thread (String threadName)

Constructs a new Thread with no Runnable object and the name provided. The new Thread will belong to the same ThreadGroup as the Thread calling this constructor.

Parameters
threadName String: the name for the Thread being created

See also:

Thread

Added in API level 1
Thread (ThreadGroup group, 
                Runnable runnable)

Constructs a new Thread with a Runnable object and a newly generated name. The new Thread will belong to the ThreadGroup passed as parameter.

Parameters
group ThreadGroup: ThreadGroup to which the new Thread will belong
runnable Runnable: a Runnable whose method run will be executed by the new Thread
Throws
IllegalThreadStateException if group.destroy() has already been done

See also:

Thread

Added in API level 1
Thread (ThreadGroup group, 
                Runnable runnable, 
                String threadName)

Constructs a new Thread with a Runnable object, the given name and belonging to the ThreadGroup passed as parameter.

Parameters
group ThreadGroup: ThreadGroup to which the new Thread will belong
runnable Runnable: a Runnable whose method run will be executed by the new Thread
threadName String: the name for the Thread being created
Throws
IllegalThreadStateException if group.destroy() has already been done

See also:

Thread

Added in API level 1
Thread (ThreadGroup group, 
                String threadName)

Constructs a new Thread with no Runnable object, the given name and belonging to the ThreadGroup passed as parameter.

Parameters
group ThreadGroup: ThreadGroup to which the new Thread will belong
threadName String: the name for the Thread being created
Throws
IllegalThreadStateException if group.destroy() has already been done

See also:

Thread

Added in API level 1
Thread (ThreadGroup group, 
                Runnable runnable, 
                String threadName, 
                long stackSize)

Constructs a new Thread with a Runnable object, the given name and belonging to the ThreadGroup passed as parameter.

Parameters
group ThreadGroup: ThreadGroup to which the new Thread will belong
runnable Runnable: a Runnable whose method run will be executed by the new Thread
threadName String: the name for the Thread being created
stackSize long: a stack size for the new Thread. This has a highly platform-dependent interpretation. It may even be ignored completely.
Throws
IllegalThreadStateException if group.destroy() has already been done

See also:

Public methods

activeCount

Added in API level 1
int activeCount ()

Returns the number of active Threads in the running Thread's group and its subgroups.

Returns
int the number of Threads

checkAccess

Added in API level 1
void checkAccess ()

Does nothing.

countStackFrames

Added in API level 1
int countStackFrames ()

This method was deprecated in API level 1.
The results of this call were never well defined. To make things worse, it would depend on whether the Thread was suspended or not, and suspend was deprecated too.

Returns the number of stack frames in this thread.

Returns
int Number of stack frames

currentThread

Added in API level 1
Thread currentThread ()

Returns the Thread of the caller, that is, the current Thread.

Returns
Thread

destroy

Added in API level 1
void destroy ()

This method was deprecated in API level 1.
Not implemented.

Throws UnsupportedOperationException.

dumpStack

Added in API level 1
void dumpStack ()

Prints to the standard error stream a text representation of the current stack for this Thread.

See also:

enumerate

Added in API level 1
int enumerate (Thread[] threads)

Copies an array with all Threads which are in the same ThreadGroup as the receiver - and subgroups - into the array threads passed as parameter. If the array passed as parameter is too small no exception is thrown - the extra elements are simply not copied.

Parameters
threads Thread: array into which the Threads will be copied
Returns
int How many Threads were copied over

getAllStackTraces

Added in API level 1
Map<ThreadStackTraceElement[]> getAllStackTraces ()

Returns a map of all the currently live threads to their stack traces.

Returns
Map<ThreadStackTraceElement[]>

getContextClassLoader

Added in API level 1
ClassLoader getContextClassLoader ()

Returns the context ClassLoader for this Thread.

Returns
ClassLoader ClassLoader The context ClassLoader

See also:

getDefaultUncaughtExceptionHandler

Added in API level 1
Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler ()

Returns the default exception handler that's executed when uncaught exception terminates a thread.

Returns
Thread.UncaughtExceptionHandler an Thread.UncaughtExceptionHandler or null if none exists.

getId

Added in API level 1
long getId ()

Returns the thread's identifier. The ID is a positive long generated on thread creation, is unique to the thread, and doesn't change during the lifetime of the thread; the ID may be reused after the thread has been terminated.

Returns
long the thread's ID.

getName

Added in API level 1
String getName ()

Returns the name of the Thread.

Returns
String

getPriority

Added in API level 1
int getPriority ()

Returns the priority of the Thread.

Returns
int

getStackTrace

Added in API level 1
StackTraceElement[] getStackTrace ()

Returns an array of StackTraceElement representing the current thread's stack.

Returns
StackTraceElement[]

getState

Added in API level 1
Thread.State getState ()

Returns the current state of the Thread. This method is useful for monitoring purposes.

Returns
Thread.State a Thread.State value.

getThreadGroup

Added in API level 1
ThreadGroup getThreadGroup ()

Returns the ThreadGroup to which this Thread belongs.

Returns
ThreadGroup the Thread's ThreadGroup

getUncaughtExceptionHandler

Added in API level 1
Thread.UncaughtExceptionHandler getUncaughtExceptionHandler ()

Returns the thread's uncaught exception handler. If not explicitly set, then the ThreadGroup's handler is returned. If the thread is terminated, then null is returned.

Returns
Thread.UncaughtExceptionHandler an Thread.UncaughtExceptionHandler instance or null.

holdsLock

Added in API level 1
boolean holdsLock (Object object)

Indicates whether the current Thread has a monitor lock on the specified object.

Parameters
object Object: the object to test for the monitor lock
Returns
boolean true if the current thread has a monitor lock on the specified object; false otherwise

interrupt

Added in API level 1
void interrupt ()

Posts an interrupt request to this Thread. The behavior depends on the state of this Thread:

  • Threads blocked in one of Object's wait() methods or one of Thread's join() or sleep() methods will be woken up, their interrupt status will be cleared, and they receive an InterruptedException.
  • Threads blocked in an I/O operation of an InterruptibleChannel will have their interrupt status set and receive an ClosedByInterruptException. Also, the channel will be closed.
  • Threads blocked in a Selector will have their interrupt status set and return immediately. They don't receive an exception in this case.

interrupted

Added in API level 1
boolean interrupted ()

Returns a boolean indicating whether the current Thread ( currentThread()) has a pending interrupt request ( true) or not (false). It also has the side-effect of clearing the flag.

Returns
boolean a boolean indicating the interrupt status

See also:

isAlive

Added in API level 1
boolean isAlive ()

Returns true if the receiver has already been started and still runs code (hasn't died yet). Returns false either if the receiver hasn't been started yet or if it has already started and run to completion and died.

Returns
boolean a boolean indicating the liveness of the Thread

See also:

isDaemon

Added in API level 1
boolean isDaemon ()

Tests whether this is a daemon thread. A daemon thread only runs as long as there are non-daemon threads running. When the last non-daemon thread ends, the runtime will exit. This is not normally relevant to applications with a UI.

Returns
boolean

isInterrupted

Added in API level 1
boolean isInterrupted ()

Returns a boolean indicating whether the receiver has a pending interrupt request (true) or not ( false)

Returns
boolean a boolean indicating the interrupt status

See also:

join

Added in API level 1
void join ()

Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies.

Throws
InterruptedException if the current thread has been interrupted. The interrupted status of the current thread will be cleared before the exception is thrown.

See also:

join

Added in API level 1
void join (long millis, 
                int nanos)

Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.

A timeout of zero means the calling thread should wait forever unless interrupted.

Parameters
millis long: The maximum time to wait (in milliseconds).
nanos int: Extra nanosecond precision
Throws
InterruptedException if the current thread has been interrupted. The interrupted status of the current thread will be cleared before the exception is thrown.

See also:

join

Added in API level 1
void join (long millis)

Blocks the current Thread (Thread.currentThread()) until the receiver finishes its execution and dies or the specified timeout expires, whatever happens first.

A timeout of zero means the calling thread should wait forever unless interrupted.

Parameters
millis long: The maximum time to wait (in milliseconds).
Throws
InterruptedException if the current thread has been interrupted. The interrupted status of the current thread will be cleared before the exception is thrown.

See also:

resume

Added in API level 1
void resume ()

This method was deprecated in API level 1.
Only useful in conjunction with deprecated method suspend().

Throws UnsupportedOperationException.

run

Added in API level 1
void run ()

Calls the run() method of the Runnable object the receiver holds. If no Runnable is set, does nothing.

See also:

setContextClassLoader

Added in API level 1
void setContextClassLoader (ClassLoader cl)

Set the context ClassLoader for the receiver.

Parameters
cl ClassLoader: The context ClassLoader

See also:

setDaemon

Added in API level 1
void setDaemon (boolean isDaemon)

Marks this thread as a daemon thread. A daemon thread only runs as long as there are non-daemon threads running. When the last non-daemon thread ends, the runtime will exit. This is not normally relevant to applications with a UI.

Parameters
isDaemon boolean
Throws
IllegalThreadStateException - if this thread has already started.

setDefaultUncaughtExceptionHandler

Added in API level 1
void setDefaultUncaughtExceptionHandler (Thread.UncaughtExceptionHandler handler)

Sets the default uncaught exception handler. This handler is invoked in case any Thread dies due to an unhandled exception.

Parameters
handler Thread.UncaughtExceptionHandler: The handler to set or null.

setName

Added in API level 1
void setName (String threadName)

Sets the name of the Thread.

Parameters
threadName String: the new name for the Thread

See also:

setPriority

Added in API level 1
void setPriority (int priority)

Sets the priority of this thread. If the requested priority is greater than the parent thread group's getMaxPriority(), the group's maximum priority will be used instead.

Parameters
priority int
Throws
IllegalArgumentException - if the new priority is greater than MAX_PRIORITY or less than MIN_PRIORITY

setUncaughtExceptionHandler

Added in API level 1
void setUncaughtExceptionHandler (Thread.UncaughtExceptionHandler handler)

Sets the uncaught exception handler. This handler is invoked in case this Thread dies due to an unhandled exception.

Parameters
handler Thread.UncaughtExceptionHandler: The handler to set or null.

sleep

Added in API level 1
void sleep (long millis, 
                int nanos)

Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds and nanoseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.

Parameters
millis long: The time to sleep in milliseconds.
nanos int: Extra nanosecond precision
Throws
InterruptedException if the current thread has been interrupted. The interrupted status of the current thread will be cleared before the exception is thrown.

See also:

sleep

Added in API level 1
void sleep (long time)

Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.

Parameters
time long: The time to sleep in milliseconds.
Throws
InterruptedException if the current thread has been interrupted. The interrupted status of the current thread will be cleared before the exception is thrown.

See also:

start

Added in API level 1
void start ()

Starts the new Thread of execution. The run() method of the receiver will be called by the receiver Thread itself (and not the Thread calling start()).

Throws
IllegalThreadStateException - if this thread has already started.

See also:

stop

Added in API level 1
void stop (Throwable throwable)

This method was deprecated in API level 1.
because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.

Throws UnsupportedOperationException.

Parameters
throwable Throwable

stop

Added in API level 1
void stop ()

This method was deprecated in API level 1.
because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.

Requests the receiver Thread to stop and throw ThreadDeath. The Thread is resumed if it was suspended and awakened if it was sleeping, so that it can proceed to throw ThreadDeath.

suspend

Added in API level 1
void suspend ()

This method was deprecated in API level 1.
May cause deadlocks.

Throws UnsupportedOperationException.

toString

Added in API level 1
String toString ()

Returns a string containing a concise, human-readable description of the Thread. It includes the Thread's name, priority, and group name.

Returns
String a printable representation for the receiver.

yield

Added in API level 1
void yield ()

Causes the calling Thread to yield execution time to another Thread that is ready to run. The actual scheduling is implementation-dependent.

This site uses cookies to store your preferences for site-specific language and display options.

Hooray!

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.