U03 Multi Threading
U03 Multi Threading
Multi-Threading Introduction
• Multithreaded programming contains two or more parts
that run concurrently
Process are heavy weight tasks that Thread are light weight tasks and use
require their own address space same address space of application
process
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
• It executes command
sequentially
• 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
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
public void run( ) -define code that constitutes new thread and will
end when method returns
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
• Higher priority threads get more CPU time than lower priority thread
achieved by Synchronization
• Key to Synchronization is concept of monitor
• All other threads have to wait until lock had been released