Java Threads Detailed Notes
Java Threads Detailed Notes
1. What is a Thread?
A thread is a lightweight process that allows parallel execution within a program. Threads run in the same memory
space but each has its own execution flow. Threads are useful for concurrent tasks like downloading files, processing
data, etc.
In single-threaded applications, all tasks are done one at a time. In multi-threaded applications, tasks can run
simultaneously.
System.out.println("Thread is running");
thread.start();
Explanation: The MyThread class extends Thread and overrides the run() method. The start() method initiates thread
execution.
thread.start();
Explanation: MyRunnable implements Runnable and defines a task. The Thread object is created and executes the task
in a separate thread.
3. Thread Lifecycle
4. Thread Methods
Key methods:
- yield(): Pauses current thread to allow other threads of the same priority to execute.
5. Synchronization
Synchronization prevents multiple threads from accessing shared resources at the same time.
Example without synchronization may lead to inconsistent results. Adding synchronized keyword ensures only one
6. Deadlock
Deadlock occurs when two or more threads are blocked forever, waiting for each other to release resources. Proper