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.lang -
Threading 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 executing -
Waiting/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 orRunnableinterface -
Lifecycle: New ā Runnable ā Running ā Waiting/Blocked ā Terminated
-
synchronizedensures thread safety -
Methods:
start(),run(),sleep(),join(),getName(), etc.
