Multithreading and Thread class method
Multithreading:
In Java, multithreading is a programming concept where two or more parts of a program (called threads) execute concurrently to maximize CPU utilization.
A thread is the smallest unit of a process.
So, when we use multithreading, a single program (process) can perform multiple tasks at the same time.
Key Points about Multithreading in Java:
- Concurrency – Multiple tasks run simultaneously within a program.
- Lightweight – Threads are smaller and faster than processes since they share the same memory space (heap).
- Independent Execution – Each thread runs independently; if one thread faces an exception, others can still continue.
- Java Support – Java provides built-in support for multithreading via:
- Thread class
- Runnable interface
- Executor framework (for advanced thread handling)
Advantages of Multithreading:
- Better CPU utilization (perform multiple operations at once).
- Faster execution (tasks run in parallel).
- Improves responsiveness (e.g., GUI apps remain responsive while performing background tasks).
Disadvantages:
- Complexity – Writing multithreaded programs is harder.
- Synchronization issues – Risk of race conditions if multiple threads access shared resources.
- Debugging difficulty – Errors may be non-deterministic.
Thread class method:
The Thread class in Java (in java.lang package) provides several important methods to create, control, and manage threads.
Commonly Used Thread Class Methods:
1)start():
Starts a new thread and calls the run() method internally.
You should never call run() directly; use start().
2)run():
Defines the task to be executed by the thread.
Must be overridden when extending Thread or implementing Runnable.