Chapter 5 Multi-Threading
Chapter 5 Multi-Threading
with Java
Presented by,
Abdalla M.,
Department of Computer Science,
Collage of Engineering and Technology,
Samara University.
1
Chapter 5
Multi threading
2
Multithreading in Java
3
Multithreading in Java
5
Multitasking
6
Multitasking
1) Process-based Multitasking
(Multiprocessing)
◦ Each process has its own address in memory i.e.
each process allocates separate memory area.
◦ Process is heavyweight.
◦ Cost of communication between the processes is
high.
◦ Switching from one process to another require
some time for saving and loading registers,
memory maps, updating lists etc.
7
Multitasking
2) Thread-based Multitasking
(Multithreading)
◦ Threads share the same address space.
◦ Thread is lightweight.
◦ Cost of communication between the thread is
low.
Note: At least one process is required for
each thread.
8
What is Thread in java
9
What is Thread in java
10
Life cycle of a Thread (Thread States)
12
Life cycle of a Thread
(Thread States)
1) New
◦ The thread is in new state if you create an
instance of Thread class but before the
invocation of start() method.
2) Runnable
◦ The thread is in runnable state after invocation
of start() method, but the thread scheduler has
not selected it to be the running thread.
13
Life cycle of a Thread
(Thread States)
3) Running
◦ The thread is in running state if the thread
scheduler has selected it.
4) Non-Runnable (Blocked)
◦ This is the state when the thread is still alive,
but is currently not eligible to run.
5) Terminated
◦ A thread is in terminated or dead state when
its run() method exits.
14
How to create thread
15
Thread class:
16
Runnable interface:
17
Starting a thread:
18
By extending Thread class:
21
Difference between pre-emptive scheduling and time
slicing
22
Difference between pre-emptive scheduling and time
slicing
23
Sleep method in java
The sleep() method of Thread class is
used to sleep a thread for the specified
amount of time.
24
Can we start a thread twice?
25
Thread Priority:
27
Thread Priority:
28
Examples
How to perform single task by multiple
threads?
How to perform multiple tasks by
multiple threads (multitasking in
multithreading)?
29
The End!!!
Thank You?
Questions?
30