|
|||||||||
| Home >> All >> java >> [ lang overview ] | PREV CLASS NEXT CLASS | ||||||||
SUMMARY: JAVADOC | SOURCE | DOWNLOAD | NESTED | FIELD | CONSTR | METHOD |
DETAIL: FIELD | CONSTR | METHOD | ||||||||
java.lang
Class Thread

java.lang.Objectjava.lang.Thread
- All Implemented Interfaces:
- Runnable
- Direct Known Subclasses:
- VMProcess.ProcessThread
Thread represents a single thread of execution in the VM. When an application VM starts up, it creates a non-daemon Thread which calls the main() method of a particular class. There may be other Threads running, such as the garbage collection thread.
Threads have names to identify them. These names are not necessarily unique. Every Thread has a priority, as well, which tells the VM which Threads should get more running time. New threads inherit the priority and daemon status of the parent thread, by default.
There are two methods of creating a Thread: you may subclass Thread and
implement the run() method, at which point you may start the
Thread by calling its start() method, or you may implement
Runnable in the class you want to use and then call new
Thread(your_obj).start().
The virtual machine runs until all non-daemon threads have died (either
by returning from the run() method as invoked by start(), or by throwing
an uncaught exception); or until System.exit is called with
adequate permissions.
It is unclear at what point a Thread should be added to a ThreadGroup, and at what point it should be removed. Should it be inserted when it starts, or when it is created? Should it be removed when it is suspended or interrupted? The only thing that is clear is that the Thread should be removed when it is stopped.
- Since:
- 1.0
| Nested Class Summary | |
static interface |
Thread.UncaughtExceptionHandler
This interface is used to handle uncaught exceptions which cause a Thread to terminate. |
| Field Summary | |
private ClassLoader |
contextClassLoader
The context classloader for this Thread. |
(package private) boolean |
daemon
Whether the thread is a daemon. |
private static Thread.UncaughtExceptionHandler |
defaultHandler
The default exception handler. |
(package private) Thread.UncaughtExceptionHandler |
exceptionHandler
The uncaught exception handler. |
(package private) ThreadGroup |
group
The group this thread belongs to. |
(package private) gnu.java.util.WeakIdentityHashMap |
locals
Thread local storage. |
static int |
MAX_PRIORITY
The maximum priority for a Thread. |
static int |
MIN_PRIORITY
The minimum priority for a Thread. |
(package private) String |
name
The thread name, non-null. |
private static long |
nextThreadId
The next thread ID to use. |
static int |
NORM_PRIORITY
The priority a Thread gets by default. |
private static int |
numAnonymousThreadsCreated
The next thread number to use. |
(package private) int |
priority
The thread priority, 1 to 10. |
(package private) Runnable |
runnable
The object to run(), null if this is the target. |
private long |
stacksize
Native thread stack size. |
(package private) Throwable |
stillborn
Was the thread stopped before it was started? |
private long |
threadId
This thread's ID. |
(package private) VMThread |
vmThread
The underlying VM thread, only set when the thread is actually running. |
| Constructor Summary | |
|
Thread()
Allocates a new Thread object. |
|
Thread(Runnable target)
Allocates a new Thread object. |
|
Thread(Runnable target,
String name)
Allocates a new Thread object. |
|
Thread(String name)
Allocates a new Thread object. |
|
Thread(ThreadGroup group,
Runnable target)
Allocates a new Thread object. |
|
Thread(ThreadGroup group,
Runnable target,
String name)
Allocate a new Thread object, with the specified ThreadGroup and name, and using the specified Runnable object's run() method to
execute. |
|
Thread(ThreadGroup group,
Runnable target,
String name,
long size)
Allocate a new Thread object, as if by Thread(group, null, name), and give it the specified stack
size, in bytes. |
|
Thread(ThreadGroup group,
String name)
Allocates a new Thread object. |
(package private) |
Thread(VMThread vmThread,
String name,
int priority,
boolean daemon)
Used by the VM to create thread objects for threads started outside of Java. |
| Method Summary | |
static int |
activeCount()
Get the number of active threads in the current Thread's ThreadGroup. |
void |
checkAccess()
Check whether the current Thread is allowed to modify this Thread. |
int |
countStackFrames()
Deprecated. pointless, since suspend is deprecated |
static Thread |
currentThread()
Get the currently executing Thread. |
void |
destroy()
Deprecated. This method was originally intended to simply destroy the thread without performing any form of cleanup operation. However, it was never implemented. It is now deprecated for the same reason as suspend(),
stop() and resume(); namely,
it is prone to deadlocks. If a thread is destroyed while
it still maintains a lock on a resource, then this resource
will remain locked and any attempts by other threads to
access the resource will result in a deadlock. Thus, even
an implemented version of this method would be still be
deprecated, due to its unsafe nature. |
(package private) void |
die()
Clean up code, called by VMThread when thread dies. |
static void |
dumpStack()
Print a stack trace of the current thread to stderr using the same format as Throwable's printStackTrace() method. |
static int |
enumerate(Thread[] array)
Copy every active thread in the current Thread's ThreadGroup into the array. |
ClassLoader |
getContextClassLoader()
Returns the context classloader of this Thread. |
static Thread.UncaughtExceptionHandler |
getDefaultUncaughtExceptionHandler()
Returns the handler used by default when a thread terminates unexpectedly due to an exception, or null if one doesn't
exist. |
long |
getId()
Returns the unique identifier for this thread. |
String |
getName()
Get this Thread's name. |
int |
getPriority()
Get this Thread's priority. |
ThreadGroup |
getThreadGroup()
Get the ThreadGroup this Thread belongs to. |
(package private) static java.util.Map |
getThreadLocals()
Returns the map used by ThreadLocal to store the thread local values. |
Thread.UncaughtExceptionHandler |
getUncaughtExceptionHandler()
Returns the handler used when this thread terminates due to an uncaught exception. |
static boolean |
holdsLock(Object obj)
Checks whether the current thread holds the monitor on a given object. |
void |
interrupt()
Interrupt this Thread. |
static boolean |
interrupted()
Determine whether the current Thread has been interrupted, and clear the interrupted status in the process. |
boolean |
isAlive()
Determine whether this Thread is alive. |
boolean |
isDaemon()
Tell whether this is a daemon Thread or not. |
boolean |
isInterrupted()
Determine whether the given Thread has been interrupted, but leave the interrupted status alone in the process. |
void |
join()
Wait forever for the Thread in question to die. |
void |
join(long ms)
Wait the specified amount of time for the Thread in question to die. |
void |
join(long ms,
int ns)
Wait the specified amount of time for the Thread in question to die. |
void |
resume()
Deprecated. pointless, since suspend is deprecated |
void |
run()
The method of Thread that will be run if there is no Runnable object associated with the Thread. |
void |
setContextClassLoader(ClassLoader classloader)
Sets the context classloader for this Thread. |
void |
setDaemon(boolean daemon)
Set the daemon status of this Thread. |
static void |
setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h)
Sets the default uncaught exception handler used when one isn't provided by the thread or its associated ThreadGroup. |
void |
setName(String name)
Set this Thread's name. |
void |
setPriority(int priority)
Set this Thread's priority. |
void |
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h)
Assigns the given UncaughtExceptionHandler to this
thread. |
static void |
sleep(long ms)
Suspend the current Thread's execution for the specified amount of time. |
static void |
sleep(long ms,
int ns)
Suspend the current Thread's execution for the specified amount of time. |
void |
start()
Start this Thread, calling the run() method of the Runnable this Thread was created with, or else the run() method of the Thread itself. |
void |
stop()
Deprecated. unsafe operation, try not to use |
void |
stop(Throwable t)
Deprecated. unsafe operation, try not to use |
void |
suspend()
Deprecated. unsafe operation, try not to use |
String |
toString()
Returns a string representation of this thread, including the thread's name, priority, and thread group. |
static void |
yield()
Yield to another thread. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
MIN_PRIORITY
public static final int MIN_PRIORITY
- The minimum priority for a Thread.
- See Also:
- Constant Field Values
NORM_PRIORITY
public static final int NORM_PRIORITY
- The priority a Thread gets by default.
- See Also:
- Constant Field Values
MAX_PRIORITY
public static final int MAX_PRIORITY
- The maximum priority for a Thread.
- See Also:
- Constant Field Values
vmThread
volatile VMThread vmThread
- The underlying VM thread, only set when the thread is actually running.
group
volatile ThreadGroup group
- The group this thread belongs to. This is set to null by
ThreadGroup.removeThread when the thread dies.
runnable
final Runnable runnable
- The object to run(), null if this is the target.
name
volatile String name
- The thread name, non-null.
daemon
volatile boolean daemon
- Whether the thread is a daemon.
priority
volatile int priority
- The thread priority, 1 to 10.
stacksize
private long stacksize
- Native thread stack size. 0 = use default
stillborn
Throwable stillborn
- Was the thread stopped before it was started?
contextClassLoader
private ClassLoader contextClassLoader
- The context classloader for this Thread.
threadId
private final long threadId
- This thread's ID.
numAnonymousThreadsCreated
private static int numAnonymousThreadsCreated
- The next thread number to use.
nextThreadId
private static long nextThreadId
- The next thread ID to use.
defaultHandler
private static Thread.UncaughtExceptionHandler defaultHandler
- The default exception handler.
locals
gnu.java.util.WeakIdentityHashMap locals
- Thread local storage. Package accessible for use by
InheritableThreadLocal.
exceptionHandler
Thread.UncaughtExceptionHandler exceptionHandler
- The uncaught exception handler.
| Constructor Detail |
Thread
public Thread()
- Allocates a new
Threadobject. This constructor has the same effect asThread(null, null,gname), where gname is a newly generated name. Automatically generated names are of the form"Thread-"+n, where n is an integer.Threads created this way must have overridden their
run()method to actually do anything. An example illustrating this method being used follows:import java.lang.*; class plain01 implements Runnable { String name; plain01() { name = null; } plain01(String s) { name = s; } public void run() { if (name == null) System.out.println("A new thread created"); else System.out.println("A new thread with name " + name + " created"); } } class threadtest01 { public static void main(String args[] ) { int failed = 0 ; Thread t1 = new Thread(); if (t1 != null) System.out.println("new Thread() succeed"); else { System.out.println("new Thread() failed"); failed++; } } }
Thread
public Thread(Runnable target)
- Allocates a new
Threadobject. This constructor has the same effect asThread(null, target,gname), where gname is a newly generated name. Automatically generated names are of the form"Thread-"+n, where n is an integer.
Thread
public Thread(String name)
- Allocates a new
Threadobject. This constructor has the same effect asThread(null, null, name).
Thread
public Thread(ThreadGroup group, Runnable target)
- Allocates a new
Threadobject. This constructor has the same effect asThread(group, target,gname), where gname is a newly generated name. Automatically generated names are of the form"Thread-"+n, where n is an integer.
Thread
public Thread(ThreadGroup group, String name)
- Allocates a new
Threadobject. This constructor has the same effect asThread(group, null, name)
Thread
public Thread(Runnable target, String name)
- Allocates a new
Threadobject. This constructor has the same effect asThread(null, target, name).
Thread
public Thread(ThreadGroup group, Runnable target, String name)
- Allocate a new Thread object, with the specified ThreadGroup and name, and
using the specified Runnable object's
run()method to execute. If the Runnable object is null,this(which is a Runnable) is used instead.If the ThreadGroup is null, the security manager is checked. If a manager exists and returns a non-null object for
getThreadGroup, that group is used; otherwise the group of the creating thread is used. Note that the security manager callscheckAccessif the ThreadGroup is not null.The new Thread will inherit its creator's priority and daemon status. These can be changed with
setPriorityandsetDaemon.
Thread
public Thread(ThreadGroup group, Runnable target, String name, long size)
- Allocate a new Thread object, as if by
Thread(group, null, name), and give it the specified stack size, in bytes. The stack size is highly platform independent, and the virtual machine is free to round up or down, or ignore it completely. A higher value might let you go longer before aStackOverflowError, while a lower value might let you go longer before anOutOfMemoryError. Or, it may do absolutely nothing! So be careful, and expect to need to tune this value if your virtual machine even supports it. - Since:
- 1.4
Thread
Thread(VMThread vmThread, String name, int priority, boolean daemon)
- Used by the VM to create thread objects for threads started outside
of Java. Note: caller is responsible for adding the thread to
a group and InheritableThreadLocal.
| Method Detail |
activeCount
public static int activeCount()
- Get the number of active threads in the current Thread's ThreadGroup.
This implementation calls
currentThread().getThreadGroup().activeCount().
checkAccess
public final void checkAccess()
- Check whether the current Thread is allowed to modify this Thread. This
passes the check on to
SecurityManager.checkAccess(this).
countStackFrames
public int countStackFrames()
- Deprecated. pointless, since suspend is deprecated
- Count the number of stack frames in this Thread. The Thread in question must be suspended when this occurs.
- Count the number of stack frames in this Thread. The Thread in question must be suspended when this occurs.
currentThread
public static Thread currentThread()
- Get the currently executing Thread. In the situation that the
currently running thread was created by native code and doesn't
have an associated Thread object yet, a new Thread object is
constructed and associated with the native thread.
destroy
public void destroy()
- Deprecated. This method was originally intended to simply destroy
the thread without performing any form of cleanup operation.
However, it was never implemented. It is now deprecated
for the same reason as
suspend(),stop()andresume(); namely, it is prone to deadlocks. If a thread is destroyed while it still maintains a lock on a resource, then this resource will remain locked and any attempts by other threads to access the resource will result in a deadlock. Thus, even an implemented version of this method would be still be deprecated, due to its unsafe nature.- Originally intended to destroy this thread, this method was never implemented by Sun, and is hence a no-op.
- Originally intended to destroy this thread, this method was never implemented by Sun, and is hence a no-op.
dumpStack
public static void dumpStack()
- Print a stack trace of the current thread to stderr using the same
format as Throwable's printStackTrace() method.
enumerate
public static int enumerate(Thread[] array)
- Copy every active thread in the current Thread's ThreadGroup into the
array. Extra threads are silently ignored. This implementation calls
getThreadGroup().enumerate(array), which may have a security check,checkAccess(group).
getName
public final String getName()
- Get this Thread's name.
getPriority
public final int getPriority()
- Get this Thread's priority.
getThreadGroup
public final ThreadGroup getThreadGroup()
- Get the ThreadGroup this Thread belongs to. If the thread has died, this
returns null.
holdsLock
public static boolean holdsLock(Object obj)
- Checks whether the current thread holds the monitor on a given object.
This allows you to do
assert Thread.holdsLock(obj).- Since:
- 1.4
interrupt
public void interrupt()
- Interrupt this Thread. First, there is a security check,
checkAccess. Then, depending on the current state of the thread, various actions take place:If the thread is waiting because of
Object.wait()55 ,sleep(long)55 , orjoin()55 , its interrupt status will be cleared, and an InterruptedException will be thrown. Notice that this case is only possible if an external thread called interrupt().If the thread is blocked in an interruptible I/O operation, in java.nio.channels.InterruptibleChannel, the interrupt status will be set, and ClosedByInterruptException will be thrown.
If the thread is blocked on a java.nio.channels.Selector, the interrupt status will be set, and the selection will return, with a possible non-zero value, as though by the wakeup() method.
Otherwise, the interrupt status will be set.
interrupted
public static boolean interrupted()
- Determine whether the current Thread has been interrupted, and clear
the interrupted status in the process.
isInterrupted
public boolean isInterrupted()
- Determine whether the given Thread has been interrupted, but leave
the interrupted status alone in the process.
isAlive
public final boolean isAlive()
- Determine whether this Thread is alive. A thread which is alive has
started and not yet died.
isDaemon
public final boolean isDaemon()
- Tell whether this is a daemon Thread or not.
join
public final void join()
throws InterruptedException
- Wait forever for the Thread in question to die.
join
public final void join(long ms)
throws InterruptedException
- Wait the specified amount of time for the Thread in question to die.
join
public final void join(long ms,
int ns)
throws InterruptedException
- Wait the specified amount of time for the Thread in question to die.
Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do not offer that fine a grain of timing resolution. Besides, there is no guarantee that this thread can start up immediately when time expires, because some other thread may be active. So don't expect real-time performance.
resume
public final void resume()
- Deprecated. pointless, since suspend is deprecated
- Resume this Thread. If the thread is not suspended, this method does nothing. To mirror suspend(), there may be a security check:
checkAccess. - Resume this Thread. If the thread is not suspended, this method does nothing. To mirror suspend(), there may be a security check:
run
public void run()
- The method of Thread that will be run if there is no Runnable object
associated with the Thread. Thread's implementation does nothing at all.
setDaemon
public final void setDaemon(boolean daemon)
- Set the daemon status of this Thread. If this is a daemon Thread, then
the VM may exit even if it is still running. This may only be called
before the Thread starts running. There may be a security check,
checkAccess.
getContextClassLoader
public ClassLoader getContextClassLoader()
- Returns the context classloader of this Thread. The context
classloader can be used by code that want to load classes depending
on the current thread. Normally classes are loaded depending on
the classloader of the current class. There may be a security check
for
RuntimePermission("getClassLoader")if the caller's class loader is not null or an ancestor of this thread's context class loader.- Since:
- 1.2
setContextClassLoader
public void setContextClassLoader(ClassLoader classloader)
- Sets the context classloader for this Thread. When not explicitly set,
the context classloader for a thread is the same as the context
classloader of the thread that created this thread. The first thread has
as context classloader the system classloader. There may be a security
check for
RuntimePermission("setContextClassLoader").- Since:
- 1.2
setName
public final void setName(String name)
- Set this Thread's name. There may be a security check,
checkAccess.
yield
public static void yield()
- Yield to another thread. The Thread will not lose any locks it holds
during this time. There are no guarantees which thread will be
next to run, and it could even be this one, but most VMs will choose
the highest priority thread that has been waiting longest.
sleep
public static void sleep(long ms)
throws InterruptedException
- Suspend the current Thread's execution for the specified amount of
time. The Thread will not lose any locks it has during this time. There
are no guarantees which thread will be next to run, but most VMs will
choose the highest priority thread that has been waiting longest.
sleep
public static void sleep(long ms,
int ns)
throws InterruptedException
- Suspend the current Thread's execution for the specified amount of
time. The Thread will not lose any locks it has during this time. There
are no guarantees which thread will be next to run, but most VMs will
choose the highest priority thread that has been waiting longest.
Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do not offer that fine a grain of timing resolution. When ms is zero and ns is non-zero the Thread will sleep for at least one milli second. There is no guarantee that this thread can start up immediately when time expires, because some other thread may be active. So don't expect real-time performance.
start
public void start()
- Start this Thread, calling the run() method of the Runnable this Thread
was created with, or else the run() method of the Thread itself. This
is the only way to start a new thread; calling run by yourself will just
stay in the same thread. The virtual machine will remove the thread from
its thread group when the run() method completes.
stop
public final void stop()
- Deprecated. unsafe operation, try not to use
- Cause this Thread to stop abnormally because of the throw of a ThreadDeath error. If you stop a Thread that has not yet started, it will stop immediately when it is actually started.
This is inherently unsafe, as it can interrupt synchronized blocks and leave data in bad states. Hence, there is a security check:
checkAccess(this), plus another one if the current thread is not this:RuntimePermission("stopThread"). If you must catch a ThreadDeath, be sure to rethrow it after you have cleaned up. ThreadDeath is the only exception which does not print a stack trace when the thread dies. - Cause this Thread to stop abnormally because of the throw of a ThreadDeath error. If you stop a Thread that has not yet started, it will stop immediately when it is actually started.
stop
public final void stop(Throwable t)
- Deprecated. unsafe operation, try not to use
- Cause this Thread to stop abnormally and throw the specified exception. If you stop a Thread that has not yet started, the stop is ignored (contrary to what the JDK documentation says). WARNINGThis bypasses Java security, and can throw a checked exception which the call stack is unprepared to handle. Do not abuse this power.
This is inherently unsafe, as it can interrupt synchronized blocks and leave data in bad states. Hence, there is a security check:
checkAccess(this), plus another one if the current thread is not this:RuntimePermission("stopThread"). If you must catch a ThreadDeath, be sure to rethrow it after you have cleaned up. ThreadDeath is the only exception which does not print a stack trace when the thread dies. - Cause this Thread to stop abnormally and throw the specified exception. If you stop a Thread that has not yet started, the stop is ignored (contrary to what the JDK documentation says). WARNINGThis bypasses Java security, and can throw a checked exception which the call stack is unprepared to handle. Do not abuse this power.
suspend
public final void suspend()
- Deprecated. unsafe operation, try not to use
- Suspend this Thread. It will not come back, ever, unless it is resumed.
This is inherently unsafe, as the suspended thread still holds locks, and can potentially deadlock your program. Hence, there is a security check:
checkAccess. - Suspend this Thread. It will not come back, ever, unless it is resumed.
setPriority
public final void setPriority(int priority)
- Set this Thread's priority. There may be a security check,
checkAccess, then the priority is set to the smaller of priority and the ThreadGroup maximum priority.
toString
public String toString()
- Returns a string representation of this thread, including the
thread's name, priority, and thread group.
die
void die()
- Clean up code, called by VMThread when thread dies.
getThreadLocals
static java.util.Map getThreadLocals()
- Returns the map used by ThreadLocal to store the thread local values.
setUncaughtExceptionHandler
public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h)
- Assigns the given
UncaughtExceptionHandlerto this thread. This will then be called if the thread terminates due to an uncaught exception, pre-empting that of theThreadGroup.- Since:
- 1.5
getUncaughtExceptionHandler
public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
Returns the handler used when this thread terminates due to an uncaught exception. The handler used is determined by the following:
- If this thread has its own handler, this is returned.
- If not, then the handler of the thread's
ThreadGroupobject is returned. - If both are unavailable, then
nullis returned (which can only happen when the thread was terminated since then it won't have an associated thread group anymore).
- Since:
- 1.5
setDefaultUncaughtExceptionHandler
public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h)
Sets the default uncaught exception handler used when one isn't provided by the thread or its associated
ThreadGroup. This exception handler is used when the thread itself does not have an exception handler, and the thread'sThreadGroupdoes not override this default mechanism with its own. As the group calls this handler by default, this exception handler should not defer to that of the group, as it may lead to infinite recursion.Uncaught exception handlers are used when a thread terminates due to an uncaught exception. Replacing this handler allows default code to be put in place for all threads in order to handle this eventuality.
- Since:
- 1.5
getDefaultUncaughtExceptionHandler
public static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
- Returns the handler used by default when a thread terminates
unexpectedly due to an exception, or
nullif one doesn't exist.- Since:
- 1.5
getId
public long getId()
- Returns the unique identifier for this thread. This ID is generated
on thread creation, and may be re-used on its death.
- Since:
- 1.5
|
|||||||||
| Home >> All >> java >> [ lang overview ] | PREV CLASS NEXT CLASS | ||||||||
SUMMARY: JAVADOC | SOURCE | DOWNLOAD | NESTED | FIELD | CONSTR | METHOD |
DETAIL: FIELD | CONSTR | METHOD | ||||||||
JAVADOC
java.lang.Thread