Learn Java multithreading and concurrency. Learn about Java thread states and different steps of multithreading with simple examples.
New Born state
When we create a thread object, the thread is born and is said to be in a new born state. At this state we can do one of the following things-
a) Schedule it for running using start() method which in turn call the run() method. Then the thread goes to the ready state or runnable state.
b) Kill it using the stop() method.
The runnable state means that the thread is ready for execution and waiting for the availability of processor. If all the Threads are of equal priority, then they are given time slots for execution in Round Robin Fashion that is FCFS manner.
This process of assigning time to Threads is known as time slicing. All the threads in this state form a queue.
Running means that the processor has given its time to the thread for its execution. Then the run() method is executed.
A thread enters into the blocked state when one of the following event occurs-
1) The thread itself or another thread calls the suspend() method. A suspended thread can be revived by using the resume() method.
2) The thread itself calls the sleep(long milisec) method. After sleeping it comes to ready state.
3) The thread calls an objects wait() method to goto waiting state . If any other thread calls the notify() method then it returns to runnable / ready state.
4) If the thread is waiting for an I/O to be completed, after I/O completion it returns to the ready state.
A blocked thread is considered as “NOT RUNNABLE” but not dead & therefore fully qualified to run again.
If a running thread ends its life when it has completed execution of its run() method . It is a natural death. However we can kill this thread forcefully, by sending the stop() method to it. A thread can be killed
- as soon as it is born, or
- while it is running , or
- even when it is in blocked state.
yield( ) : voluntarily moves the current running thread to the queued ready state.