You are on page 1of 24

MULTI-THREADING

Multi-Threading Introduction
• Multithreaded programming contains two or more parts
that run concurrently

• Threads are program parts and it defines a separate path


for execution

• Multithreading is a specialized form of Multi-tasking

• Two distinct types of multitasking are


• Process Based Model
• Thread Based Model
Process Based Model Thread Based Model
Process based model deals at application Thread based model deals with detailed
program level steps of functions / procedure

Multitasking process based model Multi tasking Thread based model


requires more overhead requires less overhead

Process are heavy weight tasks that Thread are light weight tasks and use
require their own address space same address space of application
process

Inter process communication is Inter thread communication is less


expensive and limited expensive

Context switching from one process to Context switching from one thread to
another is costly other thread is of low cost
Single Thread System
• Single Threaded Model Uses an approach called Main event loop
with pooling

• Single Thread of control run in an infinite loop with pooling a single


event

• Until a task completes it has to wait in an infinite loop in single


thread model
Single Threaded Model
• Single Thread Model is similar
to a JAVA program which have a
single flow of control

• It executes command
sequentially

• All programs which we have


seen till date are example of
single threaded model
Multi Threaded System
• All classes designed in JAVA are with Multithreading capability

• Using thread allows environment to be asynchronous

• Main loop pooling mechanism is eliminated

• One thread can pause without pausing other thread events

• When thread pauses only a single thread pauses all other thread
runs without issues
Multi Threaded System • Program that contains multiple
flow capability or control

• Example One Main Thread + Three


Other threads

• Main Thread is Main method


which is designed to create other
three threads A, B, C

• Ability of language to support


multithreading is known as
concurrency
Thread States
• Thread have several states
1. New Born Creates a
Thread Object
2. Runnable Ready to
run / Waiting for CPU time
3. Running When it utilizes
CPU time
4. Blocked When waiting
for CPU time
5. Dead Stopped Thread
Thread Priorities
• Threads are assigned priorities

• Priorities are integer values that specify relative priority

• Context Switch from one running thread to other based on priority

• Rules that determine Context Switching


• Thread can voluntarily relinquish control
• Yielding, Sleeping, Blocking, Pending I/O

• Thread can be pre-empted by a higher priority thread


• Low priority thread is preempted by Higher priority thread
• Preemptive multitasking
Multi-Threading Implementation
• Multi Threading can be implemented in JAVA by two ways
1. Extending Thread class
2. Implementing Runnable Interface
• Thread class defines several methods that help manage threads

Method Meaning
getName( ) Obtain a Thread’s Name
getPriority( ) Obtain a Thread’s Priority
isAlive( ) Determine if a thread is still running
join( ) Wait for a Thread to terminate
run( ) Entry Point of Thread
start( ) Start a Thread by Calling its run method
sleep( ) Suspend a Thread for a period of time
Main Thread
•JAVA programs execution starts Main Thread automatically
•Executes first when program execution starts
•From main Thread all other child Threads are created

•To gain handle of Thread we can create thread object using method

Method Name Function

public static currentThread( ) method return reference to main


thread

static void sleep(long misecs) causes thread to suspend for


mentioned time in milliseconds

final void setName(String set name of thread using this method


Name)

final String getName( ) Obtain name of thread


Main Thread - Example
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
Extending Thread Class
• Create a new class by extending Thread class
• New class created must override run( ) method
• start( ) method must invoke execution of Thread

Extending Thread Class – Scenario


• Thread class have other methods apart from run( ) method
• if needed to override other methods of thread class
• Only run( ) method to override then use Runnable interface
• Creating Multiple Threads .Examples
Implementing Runnable Interface
• Create a class that implements Runnable Interface

• Runnable interface have method declaration of type

public void run( ) -define code that constitutes new thread and will
end when method returns

void start( ) -method invokes run( ) method of thread to start its


execution

• Thread object is created by using following constructors


Thread(Runnable threadOb, String threadName)
Thread(Runnable threadOb)
Example refer book
Multiple Threads
class Test implements Runnable{
public void run(){
for(int i=5;i>0;i--){
System.out.println(Thread.currentThread()+" "+i);
}
}
}

class Example2{
public static void main(String args[]){
Test x=new Test();
Test y=new Test();
Test z=new Test();
Thread t1=new Thread(x,"First");
Thread t2=new Thread(y,"Second");
Thread t3=new Thread(z,"Third");
t1.start();
t2.start();
t3.start();
}
}
Using isAlive( ) and join( )
• To check whether thread is alive or not we use isAlive( ) method
provided by Thread class

final boolean isAlive( )


– it returns true if thread is still running or false otherwise

final void join( ) throws InterruptedException


– it waits for a maximum amount of time that wait for specified
thread to terminate
Thread Priorities
• Thread scheduler uses priorities to decide when each Thread is
allowed to run

• Higher priority threads get more CPU time than lower priority thread

• To set Thread priority we invoke the method


final void setPriority(int level)
specifies new priority value for calling thread

• Thread class have following final variables


MIN_PRIORITY -1
NORM_PRIORITY - 5
MAX_PRIORITY -10
Thread Priorities
• Obtain current priority of thread by invoking
final int getPriority( ) - Obtains current priority of
running thread

• Method is defined in Thread class


Synchronization
• Two or more Threads need to access a Shared Resource

• Mechanism that allows only one Thread to access the resource

achieved by Synchronization
• Key to Synchronization is concept of monitor

• Monitor is a mutually exclusive lock owned by a Thread at a time

• All other threads have to wait until lock had been released

• Synchronization can be achieved in two ways

1. Using Synchronized Methods


2. Using Synchronized Statements
Using Synchronized Methods
• synchronized keyword is used along with method block
class Callme {
synchronized void call(String msg) {
..
}
..
}

• Declaring a method synchronized allow only one thread to access


method at a time. (mutex)
Using Synchronized Statement
• General form of synchronized statement are
synchronized(object) {
// statements to be synchronized
}

• Object is a reference to object being synchronized

• Synchronized block ensures following statements be executed only


for current object that holds monitor
Inter Thread Communication
• Three methods are provided for inter thread communication
• wait( )
• tells thread to give up monitor
• go to sleep until other thread enters monitor and calls notify( )
final void wait( ) throws InterruptedException
• notify( )
• Wakes up first thread that called wait( ) on same object
final void notify( )
• notifyAll( )
• Wakes up all thread that called wait( ) on same object
• Highest priority thread will run first
final void notifyAll( )
• Methods are provided by Object class and all methods are final

• All Methods are called from synchronized context


Deadlock
• Deadlock situation is when two threads have a circular dependency
on resource utilized between them
• This occurs rarely
• When two thread uses CPU time in same way
• When more than two thread and two synchronized objects involve in program

• Few other methods of Thread class

final void suspend( ) – pause execution of thread


final void resume( ) – restart execution of thread
final void stop( ) – stop execution of thread
Thank You

You might also like