Java Threads
π§΅ Java Threads
A thread is a lightweight subprocess and the smallest unit of execution in Java.
Java allows multithreading, i.e., executing multiple threads concurrently.
Package:
java.langThreading helps in parallel execution, responsive programs, and better CPU utilization.
Β 1. Benefits of Threads
Concurrency β Multiple tasks at the same time
Improved Performance β Utilizes multiple cores
Better Resource Sharing β Threads share memory within the same process
Responsive GUI β Keeps user interface responsive
πΉ 2. Creating Threads
There are two ways to create threads in Java:
2.1 Using Thread Class
Override the
run()method.start()calls the thread; never callrun()directly for concurrency.
2.2 Using Runnable Interface
Runnableis preferred when class already extends another class.
Β 3. Thread Lifecycle
A thread goes through five states:
New β Thread object created
Runnable β Thread is ready to run
Running β
run()method executingWaiting/Blocked β Waiting for a resource or signal
Terminated β Execution finished
Β 4. Thread Methods
| Method | Description |
|---|---|
start() | Begins thread execution, calls run() |
run() | Contains code executed by thread |
sleep(ms) | Pause thread for specified milliseconds |
join() | Waits for thread to finish |
currentThread() | Returns reference to current thread |
getName() / setName() | Get or set thread name |
setPriority(int) / getPriority() | Set or get thread priority |
isAlive() | Checks if thread is alive |
Β 5. Example: Thread Sleep & Join
sleep()pauses execution temporarily.join()ensures one thread completes before another starts.
Β 6. Synchronization (Thread Safety)
Multiple threads accessing shared data can cause race conditions.
Use
synchronizedkeyword to make methods or blocks thread-safe:
Β Summary
Thread = smallest unit of execution in Java
Created using
Threadclass orRunnableinterfaceLifecycle: New β Runnable β Running β Waiting/Blocked β Terminated
synchronizedensures thread safetyMethods:
start(),run(),sleep(),join(),getName(), etc.
