|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Objectjava.lang.Thread
public class Thread
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.
Runnable
,
Runtime.exit(int)
,
run()
,
start()
,
ThreadLocal
Nested Class Summary | |
---|---|
static class |
Thread.State
Represents the current state of a thread, according to the VM rather than the operating system. |
static interface |
Thread.UncaughtExceptionHandler
This interface is used to handle uncaught exceptions which cause a Thread to terminate. |
Field Summary | |
---|---|
static int |
MAX_PRIORITY
The maximum priority for a Thread. |
static int |
MIN_PRIORITY
The minimum priority for a Thread. |
static int |
NORM_PRIORITY
The priority a Thread gets by default. |
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. |
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. |
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. |
static Map<Thread,StackTraceElement[]> |
getAllStackTraces()
Returns a map of threads to stack traces for each live thread. |
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. |
StackTraceElement[] |
getStackTrace()
Returns an array of StackTraceElement s
representing the current stack trace of this thread. |
Thread.State |
getState()
Returns the current state of the thread. |
ThreadGroup |
getThreadGroup()
Get the ThreadGroup this Thread belongs to. |
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 newPriority)
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 timeout,
int nanos)
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 |
---|
public static final int MIN_PRIORITY
public static final int NORM_PRIORITY
public static final int MAX_PRIORITY
Constructor Detail |
---|
public Thread()
Thread
object. This constructor has
the same effect as Thread(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(java.lang.ThreadGroup,
java.lang.Runnable, java.lang.String)
public Thread(Runnable target)
Thread
object. This constructor has
the same effect as Thread(null, target,
gname)
, where gname is
a newly generated name. Automatically generated names are of the
form "Thread-"+
n, where n is an integer.
target
- the object whose run
method is called.Thread(java.lang.ThreadGroup,
java.lang.Runnable, java.lang.String)
public Thread(String name)
Thread
object. This constructor has
the same effect as Thread(null, null, name)
.
name
- the name of the new thread.Thread(java.lang.ThreadGroup,
java.lang.Runnable, java.lang.String)
public Thread(ThreadGroup group, Runnable target)
Thread
object. This constructor has
the same effect as Thread(group, target,
gname)
, where gname is
a newly generated name. Automatically generated names are of the
form "Thread-"+
n, where n is an integer.
group
- the group to put the Thread intotarget
- the Runnable object to execute
SecurityException
- if this thread cannot access group
IllegalThreadStateException
- if group is destroyedThread(ThreadGroup, Runnable, String)
public Thread(ThreadGroup group, String name)
Thread
object. This constructor has
the same effect as Thread(group, null, name)
group
- the group to put the Thread intoname
- the name for the Thread
NullPointerException
- if name is null
SecurityException
- if this thread cannot access group
IllegalThreadStateException
- if group is destroyedThread(ThreadGroup, Runnable, String)
public Thread(Runnable target, String name)
Thread
object. This constructor has
the same effect as Thread(null, target, name)
.
target
- the Runnable object to executename
- the name for the Thread
NullPointerException
- if name is nullThread(ThreadGroup, Runnable, String)
public Thread(ThreadGroup group, Runnable target, String name)
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 calls
checkAccess
if the ThreadGroup is not null.
The new Thread will inherit its creator's priority and daemon status.
These can be changed with setPriority
and
setDaemon
.
group
- the group to put the Thread intotarget
- the Runnable object to executename
- the name for the Thread
NullPointerException
- if name is null
SecurityException
- if this thread cannot access group
IllegalThreadStateException
- if group is destroyedRunnable.run()
,
run()
,
setDaemon(boolean)
,
setPriority(int)
,
SecurityManager.checkAccess(ThreadGroup)
,
ThreadGroup.checkAccess()
public Thread(ThreadGroup group, Runnable target, String name, long size)
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 a
StackOverflowError
, while a lower value might let you go
longer before an OutOfMemoryError
. Or, it may do absolutely
nothing! So be careful, and expect to need to tune this value if your
virtual machine even supports it.
group
- the group to put the Thread intotarget
- the Runnable object to executename
- the name for the Threadsize
- the stack size, in bytes; 0 to be ignored
NullPointerException
- if name is null
SecurityException
- if this thread cannot access group
IllegalThreadStateException
- if group is destroyedMethod Detail |
---|
public static int activeCount()
currentThread().getThreadGroup().activeCount()
.
ThreadGroup.activeCount()
public final void checkAccess()
SecurityManager.checkAccess(this)
.
SecurityException
- if the current Thread cannot modify this ThreadSecurityManager.checkAccess(Thread)
public int countStackFrames()
IllegalThreadStateException
- if this Thread is not suspendedpublic static Thread currentThread()
public void destroy()
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.
NoSuchMethodError
- as this method was never implemented.public static void dumpStack()
Throwable.printStackTrace()
public static int enumerate(Thread[] array)
getThreadGroup().enumerate(array)
, which may have a
security check, checkAccess(group)
.
array
- the array to place the Threads into
NullPointerException
- if array is null
SecurityException
- if you cannot access the ThreadGroupThreadGroup.enumerate(Thread[])
,
activeCount()
,
SecurityManager.checkAccess(ThreadGroup)
public final String getName()
public final int getPriority()
public final ThreadGroup getThreadGroup()
public static boolean holdsLock(Object obj)
assert Thread.holdsLock(obj)
.
obj
- the object to test lock ownership on.
NullPointerException
- if obj is nullpublic void interrupt()
checkAccess
. Then, depending on the current state of the
thread, various actions take place:
If the thread is waiting because of Object.wait()
,
sleep(long)
, or join()
, 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
InterruptibleChannel
, the interrupt
status will be set, and ClosedByInterruptException will be thrown.
If the thread is blocked on a 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.
SecurityException
- if you cannot modify this Threadpublic static boolean interrupted()
isInterrupted()
public boolean isInterrupted()
interrupted()
public final boolean isAlive()
public final boolean isDaemon()
setDaemon(boolean)
public final void join() throws InterruptedException
InterruptedException
- if the Thread is interrupted; it's
interrupted status will be clearedpublic final void join(long ms) throws InterruptedException
ms
- the number of milliseconds to wait, or 0 for forever
InterruptedException
- if the Thread is interrupted; it's
interrupted status will be clearedpublic final void join(long ms, int ns) throws InterruptedException
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.
ms
- the number of milliseconds to wait, or 0 for foreverns
- the number of extra nanoseconds to sleep (0-999999)
InterruptedException
- if the Thread is interrupted; it's
interrupted status will be cleared
IllegalArgumentException
- if ns is invalidpublic final void resume()
checkAccess
.
SecurityException
- if you cannot resume the ThreadcheckAccess()
,
suspend()
public void run()
run
in interface Runnable
start()
,
Thread(ThreadGroup, Runnable, String)
public final void setDaemon(boolean daemon)
checkAccess
.
daemon
- whether this should be a daemon thread or not
SecurityException
- if you cannot modify this Thread
IllegalThreadStateException
- if the Thread is activeisDaemon()
,
checkAccess()
public ClassLoader getContextClassLoader()
RuntimePermission("getClassLoader")
if the caller's
class loader is not null or an ancestor of this thread's context class
loader.
SecurityException
- when permission is deniedsetContextClassLoader(ClassLoader)
public void setContextClassLoader(ClassLoader classloader)
RuntimePermission("setContextClassLoader")
.
classloader
- the new context class loader
SecurityException
- when permission is deniedgetContextClassLoader()
public final void setName(String name)
checkAccess
.
name
- the new name for this Thread
NullPointerException
- if name is null
SecurityException
- if you cannot modify this Threadpublic static void yield()
public static void sleep(long ms) throws InterruptedException
ms
- the number of milliseconds to sleep, or 0 for forever
InterruptedException
- if the Thread is (or was) interrupted;
it's interrupted status will be cleared
IllegalArgumentException
- if ms is negativeinterrupt()
,
Object.notify()
,
Object.wait(long)
public static void sleep(long timeout, int nanos) throws InterruptedException
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.
ms
- the number of milliseconds to sleep, or 0 for foreverns
- the number of extra nanoseconds to sleep (0-999999)
InterruptedException
- if the Thread is (or was) interrupted;
it's interrupted status will be cleared
IllegalArgumentException
- if ms or ns is negative
or ns is larger than 999999.interrupt()
,
Object.notify()
,
Object.wait(long, int)
public void start()
IllegalThreadStateException
- if the thread has already startedrun()
public final void stop()
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.
SecurityException
- if you cannot stop the Threadinterrupt()
,
checkAccess()
,
start()
,
ThreadDeath
,
ThreadGroup.uncaughtException(Thread, Throwable)
,
SecurityManager.checkAccess(Thread)
,
SecurityManager.checkPermission(Permission)
public final void stop(Throwable t)
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.
t
- the Throwable to throw when the Thread dies
SecurityException
- if you cannot stop the Thread
NullPointerException
- in the calling thread, if t is nullinterrupt()
,
checkAccess()
,
start()
,
ThreadDeath
,
ThreadGroup.uncaughtException(Thread, Throwable)
,
SecurityManager.checkAccess(Thread)
,
SecurityManager.checkPermission(Permission)
public final void suspend()
This is inherently unsafe, as the suspended thread still holds locks,
and can potentially deadlock your program. Hence, there is a security
check: checkAccess
.
SecurityException
- if you cannot suspend the ThreadcheckAccess()
,
resume()
public final void setPriority(int newPriority)
checkAccess
, then the priority is set to the smaller of
priority and the ThreadGroup maximum priority.
priority
- the new priority for this Thread
IllegalArgumentException
- if priority exceeds MIN_PRIORITY or
MAX_PRIORITY
SecurityException
- if you cannot modify this ThreadgetPriority()
,
checkAccess()
,
ThreadGroup.getMaxPriority()
,
MIN_PRIORITY
,
MAX_PRIORITY
public String toString()
toString
in class Object
Object.getClass()
,
Object.hashCode()
,
Class.getName()
,
Integer.toHexString(int)
public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h)
UncaughtExceptionHandler
to this
thread. This will then be called if the thread terminates due
to an uncaught exception, pre-empting that of the
ThreadGroup
.
h
- the handler to use for this thread.
SecurityException
- if the current thread can't modify this thread.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:
ThreadGroup
object is returned.null
is returned
(which can only happen when the thread was terminated since
then it won't have an associated thread group anymore).
UncaughtExceptionHandler
or
null
if one can't be obtained.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's ThreadGroup
does 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.
h
- the new default uncaught exception handler to use.
SecurityException
- if a security manager is present and
disallows the runtime permission
"setDefaultUncaughtExceptionHandler".public static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
null
if one doesn't
exist.
public long getId()
public Thread.State getState()
public static Map<Thread,StackTraceElement[]> getAllStackTraces()
Returns a map of threads to stack traces for each
live thread. The keys of the map are Thread
objects, which map to arrays of StackTraceElement
s.
The results obtained from Calling this method are
equivalent to calling getStackTrace()
on each
thread in succession. Threads may be executing while
this takes place, and the results represent a snapshot
of the thread at the time its getStackTrace()
method is called.
The stack trace information contains the methods called by the thread, with the most recent method forming the first element in the array. The array will be empty if the virtual machine can not obtain information on the thread.
To execute this method, the current security manager
(if one exists) must allow both the
"getStackTrace"
and
"modifyThreadGroup"
RuntimePermission
s.
StackTraceElement
s.
SecurityException
- if a security manager exists, and
prevents either or both the runtime
permissions specified above.getStackTrace()
public StackTraceElement[] getStackTrace()
Returns an array of StackTraceElement
s
representing the current stack trace of this thread.
The first element of the array is the most recent
method called, and represents the top of the stack.
The elements continue in this order, with the last
element representing the bottom of the stack.
A zero element array is returned for threads which have not yet started (and thus have not yet executed any methods) or for those which have terminated. Where the virtual machine can not obtain a trace for the thread, an empty array is also returned. The virtual machine may also omit some methods from the trace in non-zero arrays.
To execute this method, the current security manager
(if one exists) must allow both the
"getStackTrace"
and
"modifyThreadGroup"
RuntimePermission
s.
SecurityException
- if a security manager exists, and
prevents the use of the
"getStackTrace"
permission.getAllStackTraces()
|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |