A thread is a basic processing unit to which an operating system allocates processor time, and more than one thread can be executing code inside a process.
(Java 5: A Beginner's Tutorial by Budi Kurniawan Brainy Software Corp. 2006
Every Java program has at least one thread, the thread that executes the Java program.
It is created when you invoke the static main method of your Java class.
There are two ways to create a thread.
- Extend the java.lang.Thread class
- Implement the java.lang.Runnable interface.
- Once you have a Thread object, you call its start method to start the thread.
- When a thread is started, its run method is executed.
- Once the run method returns or throws an exception, the thread dies and will be garbage-collected.
Every Thread has a state and a Thread can be in one of these six states.
- new. A state in which a thread has not been started.
- runnable. A state in which a thread is executing.
- blocked. A state in which a thread is waiting for a lock to access an object.
- waiting. A state in which a thread is waiting indefinitely for another thread to perform an action.
- timed__waiting. A state in which a thread is waiting for up to a specified period of time for another thread to perform an action.
- terminated. A state in which a thread has exited.
The values that represent these states are encapsulated in the java.lang.Thread.State enum.
The members of this enum are NEW, RUNNABLE, BLOCKED, WAITING, TIMED__WAITING, and TERMINATED.