Chapter 8 Multithreading
Chapter 8 Multithreading
IN JAVA
Pratima Sarkar
CSE TINT
Table of Contents
• What is Thread?
• Creating Java Threads
• Extending the Threads Class
• Stopping and Blocking a Thread Life cycle of a
Thread
• Using Thread methods,
• Thread Exceptions,
• Thread priority
• Synchronization,
• Implementing the ‘Runnable’ Interface.
Introduction
• Difference between program and process.
– A program is a set of instructions that are written to perform a
designated task.
– A process is an operation which takes the given particular instructions
and perform the manipulations. (Program in execution)
Main Method
module
Switching Switching
• Multithreaded programs are the programs that contains multiple
flow of control.
Introduction
• A thread is a single tiny programs (or module) that runs in parallel with
other.
1. By creating a thread class: Define a class that extends Thread Class and
override its run() method with the code required by the thread.
4. Syntax for creating a thread and run an instance of our own thread class:
MyThread aThread= new MyThread();
aThread.start();
Example
Class A extends Thread Class MyThread
{ public void run() {
{ …….. P.S.V.M(String args[])
…….. {
} A aThread= new A();
} B bThread= new B();
Class B extends Thread C cThread= new C();
{ public void run()
{ …….. aThread.start();
…….. bThread.start();
} cThread.start();
}
Class C extends Thread }
{ public void run() }
{ ……..
……..
}
}
Thread Life Cycle model
• A thread can be in one of the five states (New, Runnable, Running,
Blocked, Dead)
New Born
Active Thread Start Stop
Stop
Running Runnnable Dead
Yield
3. Running: The thread is in running state if the thread scheduler has selected
it.
4. Blocked (Non-Runnable): This is the state when the thread is still alive, but
is currently not eligible to run.(Prevented from entering runnable state)
• This can be achieved by the thread object and initiating it with the
help of another method called start().
}
Synchronization
Synchronization in java is the capability to control the
access of multiple threads to any shared resource.
}
Use of synchronized method to achieve
synchronization.
class A extends Thread class syn12
{ A a;
static int i=0; {
A() { } p.s.v.m(String args[])
A(A x) { a=x; }
public void run() {
{ a.print(); }//end run A a1=new A();
synchronized void print()
{ A a2=new A(a1);
try{ i=i+5; A a3=new A(a1);
Thread.sleep(1000);
SOP("value of i : "+i);
} a2.start();
catch(InterruptedException e)
a3.start(); Output
{ SOP("error"); }
Value of i : 5
}//end print } Value of i : 10
}
}