Multithreading
Multithreading
Process
Processes are basically the programs
that are dispatched from the ready state
and are scheduled in the CPU for
execution
Multithreading
It is a process of executing multiple threads
simultaneously.
Program
Running of the multiple portion of the program at a
same time
Thread Synchronization
It is a option where we want to allow only one thread to
access the shared resource.
It is used to prevent thread interference.
It is used to prevent consistency problem
It can be used with method, variables and blocks
Example: Producer-Consumer
Multitasking vs Multithreading
Multitasking Multithreading
Multi-tasking is the ability of Execution of the multi
an operating system to run threads at a same time of a
multiple processes or tasks same program sharing the
concurrently, sharing the memory area
same processor and other It is the feature of
resources. programming language
It is the feature of operating
system
Advantages of Multithreading
1. It doesn’t block the user because threads are
independent and you can perform multiple
operations at the same time
2. You can perform many operations together so it saves
time
3. Threads are independent, so it doesn’t affect other
threads if an exception occurs in a single thread
Applications of Multithreading
1. It is used in video games
2. It is used to create media players
3. It is used to build servers
4. It is used in web browsers to load multiple web pages
at the same time
5. Used by the Databases
Thread Creation in Java
Using Thread Class
We can use extends the Thread class provided by Java.lang
package and write code in run() method
CPU
T1
T0
Working of Start method
What if we call run instead of start method
Life Cycle of Thread
Life Cycle method of a Thread
1. New
When a new thread is created using new keyword
2. Runnable
Thread is created and present in thread pool to get execute
3. Running
Thread is currently executing by the CPU
4. Waiting
Thread is waiting or timed waiting for other threads to gets complete
their task
5. Dead
Execution of the thread is done by the processor
Different Methods
Sleep()
Join()
Notify()
notifyAll()
Wait()
Some other concepts
Thread Name
Thread Priority