Thread Life Cycle
A thread in Java can be in one of several states during its life cycle. Here's a breakdown of each state:
New:
A thread is in this state when it is created but not yet started.
Example: Thread t = new Thread();
Runnable:
When the start() method is called on the thread, it moves to the Runnable state.
In this state, the thread is ready to run and waiting for the CPU time to execute.
Example: t.start();
Blocked:
A thread is in the Blocked state when it is waiting to acquire a lock to enter a synchronized block or method.
It moves to the Runnable state once it acquires the lock.
Waiting:
A thread is in the Waiting state when it is waiting indefinitely for another thread to perform a particular action.
This happens when a thread calls methods like Object.wait() or Thread.join() without a timeout.
The thread remains in this state until another thread signals it to resume execution.
Timed Waiting:
Similar to the Waiting state, but the thread waits for a specified amount of time before it either moves to the Runnable state or remains in Timed Waiting if the time expires.
Example: Thread.sleep(time) or Object.wait(time).
Terminated:
The thread has completed its execution and is no longer runnable.
Example: After the run() method completes, the thread enters the Terminated state.
Synchronization
Synchronization is used in Java to control the access of multiple threads to shared resources. Without synchronization, multiple threads might modify a shared resource concurrently, leading to inconsistent or corrupted data.
Key Concepts in Synchronization:
Synchronized Block:
You can synchronize a block of code to ensure that only one thread at a time can execute that block on a particular object.
Synchronized Method:
A method can be declared synchronized, ensuring that only one thread at a time can execute this method on an object.