Multithreadinglec
Multithreadinglec
Multithreading
• Executing program with multiple threads in parallel.
• Multithreaded program contains two or more parts that can run
concurrently. Each part is called a thread and each part defines a
separate path of execution.
• Special form of multitasking
Multitasking
• Process-based
• Thread-based
Process
• A program in execution
• A computational unit in a system which uses the resources of
system when allocated by OS.
• A heavy weight entity
Has own address space – variables and data structure in memory.
May use file utility.
• Kernel-level controlled entity.
• Communicate via OS, files, networks.
• May contain multiple threads.
Thread
• Sequentially executed stream of instructions.
•A light weight entity
Multiple threads of a process share common address space and data
of the process.
Does not use file utility.
• process level controlled entity
Why Multithreading?
• Problem solving
May have concurrent interacting components
Can handle each component using separate thread
Simplifies programming for problem
Example:
WEB BROWSER
WEB BROWSER
Web
WEB BROWSER Server
Multiple simultaneous
web browser requests Handled faster by multiple Web
Servers
Java Threads
• Java’s multithreading is built upon Thread class and its companion
interface Runnable.
• To create a thread
Implement Runnable or
Extend Thread
Specify the work we want the thread to do
Put the work in run( ) method
Thread t=Thread.currentThread( );
try{
An exception is thrown if
for(int i=5;i>0;i--) { System.out.println(i); some other thread want
to interrupt the sleeping
Thread.sleep(1000);} //pausiing for one second;
thread
}catch(InterruptedException e){System.out.println(“Main Thread interrupted”);}
}
}
Creating a Thread using Runnable
interface
• To implement Runnable a class need only implement a single
method run( ) which defines the code that constitutes the new
thread
• run( ) can call other methods, use classes and declare variables just
like main thread can.
• run( ) establishes an entry point for another concurrent thread of
execution within our program. This thread will end when run( )
returns.
• After implementing Runnable
instantiate an object of type thread within the class
Call the start method to start the new thread
run( ) executes a call to run( )
class NewThread implements Runnable{
Thread t;
NewThread( ){
t = new Thread(this,”DemoThread”); //Constructor of thread class to
System.out.println(“Child thread:” +t); instantiate Thread class
t.start( ); }
public void run( ){
try{
for(int i=5;i>0;i--) { System.out.println(“Child Thread”+i);
Thread.sleep(500);}
}catch(InterruptedException e){System.out.println(“Child Thread interrupted”);}
System.out.println(“Exiting Child Thread”);} }
class NewThreadDemo{
public static void main(String args[]){
new NewThread( ); //Create new thread
try{
for(int i=1;i<=5;i+) { System.out.println(“Main Thread:”+i);
Thread.sleep(1000);} //sleep 1000ms to ensure that main finishes last
}catch(InterruptedException e){System.out.println(“Main Thread interrupted”);}
System.out.println(“Exiting main thread”);} }
Creating a thread by extending
Thread class
• Create a new class that extends Thread
• Create an instance of that class
• The extending method must override the run method
• Must also call start( ) method to begin execution of new thread
class NewThread extendsThread{
//Thread t; no need to create this reference as Thread is already being inherited
NewThread( ){
Super(“DemoThread); //Constructor of super class
System.out.println(“Child thread:” +this); Thread is called
start( ); }
public void run( ){
try{
for(int i=5;i>0;i--) { System.out.println(“Child Thread”+i);
Thread.sleep(500);}
}catch(InterruptedException e){System.out.println(“Child Thread interrupted”);}
System.out.println(“Exiting Child Thread”);} }
class NewThreadDemo{
public static void main(String args[]){
new NewThread( ); //Create new thread
try{
for(int i=1;i<=5;i+) { System.out.println(“Main Thread:”+i);
Thread.sleep(1000);} //sleep 1000ms to ensure that main finishes last
}catch(InterruptedException e){System.out.println(“Main Thread interrupted”);}
System.out.println(“Exiting main thread”);} }
Extending Thread class (not
recommended)
• The Thread class defines several methods that can be overridden
by a subclass.
• run( ) is the only one method that must be overridden, the same
method is required when we implement Runnable.
• In general the classes should be extended only when they are being
enhanced or modified in some way. So if no other Thread’s method
are overridden then implement Runnable.
Creating multiple threads
• Our program can spawn as many threads as it needs.
• Once started all threads share same CPU.
• Example:- Two threads are created with different names.
class NewThread implements Runnable{
Thread t; String name;
NewThread(String threadname ){ name=threadname;
t = new Thread(this,name); //Constructor of thread class to
System.out.println(“New thread:” +t); instantiate Thread class
t.start( ); }
public void run( ){
try{
for(int i=5;i>0;i--) { System.out.println(name+ “ :” +i);
Thread.sleep(1000);}
}catch(InterruptedException e){System.out.println(name+ “Thread
System.out.println(name+
interrupted”);} “Exiting ”);} }
class MultiThreadDemo{
public static void main(String args[]){
new NewThread(“ONE” ); new NewThread(“SECOND” ); //Create new threads
try{
for(int i=1;i<=5;i+) { System.out.println(“Main Thread:”+i);
Thread.sleep(10000);}//sleep 1000ms to ensure that main finishes last
}catch(InterruptedException e){System.out.println(“Main Thread interrupted”);}
System.out.println(“Exiting main thread”);} }
Synchronization
• Websters: “To represent or arrange events to indicate coincidence
or coexistence.”
• Lewis : “To arrange events so that they occur in a specified order.”
• Serialized access to controlled resources.
• Thread Synchronization
On shared memory : shared variables – semaphores
On distributed memory:-
within a task – semaphores
across the task – by passing messages
Concurrent Execution
• More than one thread exists in system at once
• Can execute independently or in cooperation
• Asynchronous execution
Threads generally independent
Must occasionally communicate or synchronize
Complex and difficult to manage such interactions
Atomic actions
• An action which must be started and completed with no possibility of
interruption.
A machine instruction could need to be atomic. (not all are!)
A line of C code could need to be atomic. (not all are)
An entire database transaction could need to be atomic.
Shared Data
Critical Section
(Good Programmer!)
T1 T2
Reader{ Writer{
------------------- -------------------
Lock(DISK) Lock(DISK)
………………… …………………
………………… …………………
Unlock(DISK) Unlock(DISK)
} }
Shared Data
Lock Shared Data!
• Globals
• Shared data structures
• Static variables
(really just lexically scoped global variables)
Mutual Exclusion
Thread 1 Thread2
class Q{
int n;
Synchronized int get( ){
System.out.println(“Got: “ +n);
return n;
}
Process 1 Process 2
Synchronization
Variable S S
Shared Memory
S
Thread S