Multhreading in Java is a process that enables a program to run multiple threads simultaneously , allowing multiple tasks to execute in parallel and utilize the CPU more efficiently . A thread is an independent , lightweight unit of execution inside a java program .
Threads allow parallel execution of tasks .
A process can have multiple threads.
Each thread runs independently but shares the same memory.
CORE CONCEPTS OF JAVA MULTITHREADING :
- Thread :Thread is the smallest unit of execution .
- Process : Process is an independent program in execution. One process can contain multiple threads that share the same memory .
- Concurrency vs. Parallelism :
- Parallelism is when tasks are running at the exact same moment on different CPU cores.
- Concurrency is when tasks overlap in time
CREATING THREADS :
There are two ways to create a thread .
- Extending the Thread class : Create a class that inherits the Thread class and override its run() method .
- Implementing the Runnable Interface: Create a new class which implements java.lang.Runnable interface and define the run() method there . Then instantiate a Thread object and call start() method on this object .
- Executor Framework : Use the ExecutorService for professional applications to manage the Thread Pool , which reuses existing threads instead of constantly creating new ones .
Thread Lifecycle :
A thread moves through several states managed by the JVM.
- New : This state explain thread is created but not yet started .
- Runnable : This state explain thread is ready to run and waiting for CPU time.
- Running : This state explains actively executing code
- Blocked/Waiting : This state explains paused thread because it’s waiting for resources or another thread.
- Terminated : This state explains thread task is finished or stopped .
Synchronized & Thread Safety :
When multiple threads access the same data, they can cause a Race Condition where final result is unpredictable . These concepts to helps to resolve such problems.
- synchronized Keyword : This keyword is used on methods or blocks to ensure that only one thread can enter that code at a time .
- Volatile : The volatile keyword ensures that if one thread made changes to a variable , then it is visible to all other threads immediately .
- Locks : The Lock class provides more advanced control than synchronized .
