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

  1. Concurrency – Multiple tasks at the same time

  2. Improved Performance – Utilizes multiple cores

  3. Better Resource Sharing – Threads share memory within the same process

  4. 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 call run() directly for concurrency.


2.2 Using Runnable Interface


 

  • Runnable is preferred when class already extends another class.


Ā 3. Thread Lifecycle

A thread goes through five states:

  1. New – Thread object created

  2. Runnable – Thread is ready to run

  3. Running – run() method executing

  4. Waiting/Blocked – Waiting for a resource or signal

  5. 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 synchronized keyword to make methods or blocks thread-safe:


 


Ā Summary

  • Thread = smallest unit of execution in Java

  • Created using Thread class or Runnable interface

  • Lifecycle: New → Runnable → Running → Waiting/Blocked → Terminated

  • synchronized ensures thread safety

  • Methods: start(), run(), sleep(), join(), getName(), etc.

You may also like...