Class Thread
- java.lang.Object
-
- java.lang.Thread
-
- All Implemented Interfaces:
- Runnable
- Direct Known Subclasses:
- ForkJoinWorkerThread
public class Thread extends Object implements Runnable
A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new
Threadobject, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named
mainof some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:- The
exitmethod of classRuntimehas been called and the security manager has permitted the exit operation to take place. - All threads that are not daemon threads have died, either by returning from the call to the
runmethod or by throwing an exception that propagates beyond therunmethod.
There are two ways to create a new thread of execution. One is to declare a class to be a subclass of
Thread. This subclass should override therunmethod of classThread. An instance of the subclass can then be allocated and started. For example, a thread that computes primes larger than a stated value could be written as follows:
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 declare a class that implements the
Runnableinterface. That class then implements therunmethod. An instance of the class can then be allocated, passed as an argument when creatingThread, and started. The same example in this other style looks like the following:
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 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.
Unless otherwise noted, passing a
nullargument to a constructor or method in this class will cause aNullPointerExceptionto be thrown.- Since:
- JDK1.0
- See Also:
Runnable,Runtime.exit(int),run(),stop()
-
-
Nested Class Summary
Modifier and Type Class and Description static classThread.StateA thread state.static interfaceThread.UncaughtExceptionHandlerInterface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.
-
Field Summary
Modifier and Type Field and Description static intMAX_PRIORITYThe maximum priority that a thread can have.static intMIN_PRIORITYThe minimum priority that a thread can have.static intNORM_PRIORITYThe default priority that is assigned to a thread.
-
Constructor Summary
Constructor and Description Thread()Allocates a newThreadobject.Thread(Runnable target)Allocates a newThreadobject.Thread(Runnable target, String name)Allocates a newThreadobject.Thread(String name)Allocates a newThreadobject.Thread(ThreadGroup group, Runnable target)Allocates a newThreadobject.Thread(ThreadGroup group, Runnable target, String name)Allocates a newThreadobject so that it hastargetas its run object, has the specifiednameas its name, and belongs to the thread group referred to bygroup.Thread(ThreadGroup group, Runnable target, String name, long stackSize)Allocates a newThreadobject so that it hastargetas its run object, has the specifiednameas its name, and belongs to the thread group referred to bygroup, and has the specified stack size.Thread(ThreadGroup group, String name)Allocates a newThreadobject.
-
-
Method Summary
Modifier and Type Method and Description static intactiveCount()Returns an estimate of the number of active threads in the current thread's thread groupand its subgroups.voidcheckAccess()Determines if the currently running thread has permission to modify this thread.protected Objectclone()Throws CloneNotSupportedException as a Thread can not be meaningfully cloned.intcountStackFrames()Deprecated.The definition of this call depends onsuspend(), which is deprecated. Further, the results of this call were never well-defined.static ThreadcurrentThread()Returns a reference to the currently executing thread object.voiddestroy()Deprecated.This method was originally designed to destroy this thread without any cleanup. Any monitors it held would have remained locked. However, the method was never implemented. If if were to be implemented, it would be deadlock-prone in much the manner ofsuspend(). If the target thread held a lock protecting a critical system resource when it was destroyed, no thread could ever access this resource again. If another thread ever attempted to lock this resource, deadlock would result. Such deadlocks typically manifest themselves as "frozen" processes. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.static voiddumpStack()Prints a stack trace of the current thread to the standard error stream.static intenumerate(Thread[] tarray)Copies into the specified array every active thread in the current thread's thread group and its subgroups.static Map<Thread,StackTraceElement[]>getAllStackTraces()Returns a map of stack traces for all live threads.ClassLoadergetContextClassLoader()Returns the context ClassLoader for this Thread.static Thread.UncaughtExceptionHandlergetDefaultUncaughtExceptionHandler()Returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.longgetId()Returns the identifier of this Thread.StringgetName()Returns this thread's name.intgetPriority()Returns this thread's priority.StackTraceElement[]getStackTrace()Returns an array of stack trace elements representing the stack dump of this thread.Thread.StategetState()Returns the state of this thread.ThreadGroupgetThreadGroup()Returns the thread group to which this thread belongs.Thread.UncaughtExceptionHandlergetUncaughtExceptionHandler()Returns the handler invoked when this thread abruptly terminates due to an uncaught exception.static booleanholdsLock(Object obj)Returns true if and only if the current thread holds the monitor lock on the specified object.voidinterrupt()Interrupts this thread.static booleaninterrupted()Tests whether the current thread has been interrupted.booleanisAlive()Tests if this thread is alive.booleanisDaemon()Tests if this thread is a daemon thread.booleanisInterrupted()Tests whether this thread has been interrupted.voidjoin()Waits for this thread to die.voidjoin(long millis)Waits at mostmillismilliseconds for this thread to die.voidjoin(long millis, int nanos)Waits at mostmillismilliseconds plusnanosnanoseconds for this thread to die.voidresume()Deprecated.This method exists solely for use withsuspend(), which has been deprecated because it is deadlock-prone. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.voidrun()If this thread was constructed using a separateRunnablerun object, then thatRunnableobject'srunmethod is called; otherwise, this method does nothing and returns.voidsetContextClassLoader(ClassLoader cl)Sets the context ClassLoader for this Thread.voidsetDaemon(boolean on)static voidsetDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.voidsetName(String name)Changes the name of this thread to be equal to the argumentname.voidsetPriority(int newPriority)Changes the priority of this thread.voidsetUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)Set the handler invoked when this thread abruptly terminates due to an uncaught exception.static voidsleep(long millis)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.static voidsleep(long millis, int nanos)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.voidstart()Causes this thread to begin execution; the Java Virtual Machine calls therunmethod of this thread.voidstop()Deprecated.This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the uncheckedThreadDeathexception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses ofstopshould be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), theinterruptmethod should be used to interrupt the wait. For more information, seeWhy are Thread.stop, Thread.suspend and Thread.resume Deprecated?.voidstop(Throwable obj)Deprecated.This method is inherently unsafe. Seestop()for details. An additional danger of this method is that it may be used to generate exceptions that the target thread is unprepared to handle (including checked exceptions that the thread could not possibly throw, were it not for this method). For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.voidsuspend()Deprecated.This method has been deprecated, as it is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to callingresume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.StringtoString()Returns a string representation of this thread, including the thread's name, priority, and thread group.static voidyield()A hint to the scheduler that the current thread is willing to yield its current use of a processor.
'Dev. 자바 > API 및 이론' 카테고리의 다른 글
| [JAVA API] java.net.InetAddress (0) | 2012.09.06 |
|---|---|
| [JAVA API] java.net.URL (0) | 2012.09.06 |
| [JAVA API] java.util.HashSet<E> (0) | 2012.09.01 |
| [JAVA API] java.io.FileWriter (0) | 2012.08.08 |
| [JAVA API] java.io.FileReader (0) | 2012.08.08 |