Final Unit-V-Multithreading
Final Unit-V-Multithreading
Contents:-
Thread Priorities
Synchronization
Inter-thread Communication
1
Multithreading
Multithreading means a single program having different threads executing independently
at the same time.
A thread represents an individual path of execution. By such division we can save the
wastage of CPU time in a process.
Process Based
Thread Based
2
Multithreading
Process Based
Thread Based:
3
Multithreading
Process Based Multitasking (Multithreading):
Each process have its own address in memory i.e. each process allocates separate memory
area.
Process is heavyweight.
Switching from one process to another require some time for saving and loading registers,
4
Multithreading
Difference between Process & Thread:
Process is Smallest Unit Thread is Smallest Unit
If working Thread suspends any other Thread will take on CPU time and starts working.
Hence, no wastage of CPU time.
6
Multithreading
7
Multithreading
8
Multithreading
Demonstrating main( ) thread:
Code-1:
Daemon thread is a low priority thread which runs intermittently in the background
doing the garbage collection operation for the java runtime system.
9
Multithreading
The Runnable interface holds run( ) method which holds logic of thread. We can write a
class implementing Runnable interface and overriding run( ) method.
Creating child thread means creating object of ‘Thread’ class, for this purpose Java
provides following two constructor.
Thread(Runnable Obj)
Thread(Runnable Obj, String ThreadName)
After creating thread we need to start it so that it should begin the execution of its run( )
method. For this purpose Java provides following two method of ‘Thread’ class.
void start( );
t.start( );
Code-2:
10
Multithreading
Note: Control of the program cannot be passed to the Thread because Thread works
randomly and concurrently.
Code-3:
Code-4:
11
Multithreading
Extending Thread: When any class extends Thread class the object of that class becomes child
Thread.
Code-5:
Runnable(Interface) VS Thread(Class):
It is a little confusing why there are two ways of doing the same thing in the threading API.
It is important to understand the implication of using these two different approaches. By
extending the thread class, the derived class itself is a thread object and it gains full control
over the thread life cycle.
Implementing the Runnable interface does not give developers any control over the thread
itself, as it simply defines the unit of work that will be executed by a thread.
Another important point is that when extending the Thread class, the derived class cannot
extend any other base classes because Java only allows single inheritance.
By implementing the Runnable interface, the class can still extend other base classes if
necessary.
To summarize, if the program needs a full control over the thread life cycle, extending the
Thread class is a good choice, and if the program needs more flexibility of extending other
base classes, implementing the Runnable interface would be preferable. If none of these is
present, either of them is fine to use.
12
Multithreading
13
Multithreading
born
start
ready
dispatch
quantum (assign a
processor)
expiration
running
Sleep intervals
resume
expires
stop complete
dead 12
14
Multithreading
1.New: When Thread is created using new operator, it is in born state not in running state.
When thread is in born state no code inside it is being executed.
2.Runnable: (Ready to run) Once the start( ) method is invoked the thread is in ready to run
state. It may not be yet running .It is up to the operating system to schedule the thread
execution. If it gets the CPU time and we start thread it comes in Runnable state.
15
Multithreading
Life Cycle of Thread:
3.RunningState:Once the thread goes to running state or starts execution, it acquires CPU time
and memory and it executes its logic.
4.BlockedState:When the thread is in running state and is suspended due to any reason, it is in
blocked state. After the end of the block state, thread comes in Runnable state.
The thread enters blocked state when one of the following event occurs:
Someone calls sleep( ) method of Thread class.
The Thread is moved back to Runnable state from blocked state when one of the following
occurs:
If the thread is put to sleep( ), the specified sleep time elapsed
If the thread is suspended, another thread calls its resume( ) method
If the thread is blocked by calling an wait( ), then can be resumed by calling notify( ), notify
All( ).
If the thread is blocked on I/O, the specified I/O operation completes.
16
Multithreading
Life Cycle of Thread:
5.Dead: After completion of its logic thread goes in dead state. A thread is dead for one of the
following reasons:
It dies a natural death because the run( ) method exits.
Code-7:
17
Multithreading
Thread Priority:
18
Multithreading
Thread Priority:
If multiple threads of a process are working concurrently and running thread of a process is suspended
or terminated or blocked, then which thread among runnable state threads will take on CPU time? (The
thread with highest priority has more chances.)
If multiple threads of a process are working concurrently for specified time period then which thread
will take on how much CPU time? (The thread with higher priorities will utilize most of the CPU
Time).
To specify thread priority, java provides following 3 static & final integer variables of ‘Thread’
class:--
Thread.MIN_PRIORITY Value=1
Thread.NORM_PRIORITY Value=5
Thread.MAX_PRIORITY Value=10
19
Multithreading
Thread Priority:
To set & get thread priorities, java provides following methods of ‘Thread’ Class:--
Code-8:
20
Multithreading
Synchronization:
With respect to multithreading, synchronization is the capability to control the access of multiple
threads to shared same resources. Without synchronization, it is possible for one thread to modify
a shared object while another thread is in the process of using or updating that object's value.
This often leads to significant errors.
When a common resource in memory is being utilize by multiple clients concurrently, some
logical problem may raise in system due to concurrency. Such system is known as Asynchronous
System.
In multithreading code also when an object in memory is accessed by multiple threads
concurrently partially or fully, system may become asynchronous. But every object in memory in
Java is covered by monitor or Semaphore. By default this monitor is deactivated. When we
activate this monitor, no two threads can access that object or part of object concurrently but
they can access it one by one. This automatically synchronizes system.
No two threads can access same object concurrently in memory at same point of time.
21
Multithreading
Synchronization:
22
Multithreading
Synchronization:
Code-9: 23
Multithreading
24
Multithreading
Inter -thread Communication:
T2 thread cannot access write() method because it is under monitor( read() and write() is
synchronized)
T3 can access meth () method because it is not synchronized
How much time CPU will take to complete a task is not determined by multithreading
25
Multithreading
Inter-thread Communication:
Monitor is used to lock the resources. Without synchronization we can not get the effect of
Interthread communication.
Though thread represents an individual path of execution, many times threads hold some logic
which effect each-other. Many times this dependency may lead to some unexpected results of
program. This can be avoided by establishing communication among threads.
sleep() method of Thread class suspends the thread but does not leave the monitor.
wait() method of object class suspends the thread(T1) and leaves the monitor and remains
suspended till (T2)thread will not call notifyAll() method.
T2 thread will call notify() method then thread T1 will again starts executing its logic.
27
Multithreading
Interthread communication:
28
Multithreading
Interthread communication:
wait() sleep()
wait() method releases the lock. The sleep() method doesn't releases the
lock.
Code-10:
Code-11:
29