SlideShare a Scribd company logo
1 of 50
Multithreading
Monika Mishra
14IT10
Process
 An executing instance of a program is called process.
 Also known as “Heavyweight process”.
 It has own address space.
 For example while writing java program in editor we can run MP3 player. At the same time we can download
file from net. All these task are executing simultaneously and independent of each other.
Process 1 Process 2 Process 3 Process 4
CPU
What is Thread?
 A thread is a single sequential flow of execution within a program.
 A thread is a subset of process.
 Thread is considered as “Light Weight Process” because it use less resource than process.
 They share the address space of the process but process have their own address space.
 JVM create the thread whose task is to define the main thread.
Aprogram
Aprogram
A Single Threaded Program
class ABC
{
……….
...……..
……….
...……..
……….
...……..
}
Beginning
Single-threaded
Body of Execution
End
Application Thread
When we execute an application:
1. The JVM creates a Thread object whose task is defined by the main()
method .
2. The JVM starts the thread .
3. The thread executes the statements of the program one by one.
4. After executing all the statements, the method returns and the thread dies.
Difference between Process and Threads
Process Thread
 Process can be divided into
multiple threads
 Each process has its own memory
space
 It is difficult to create a process
 Threads cannot be sub divided.
 Threads of the same process share
a common memory space.
 It is easy to create a thread
MULTITHREADING
The process of executing multiple threads simultaneously is known as multithreading.
Example
 Games are very good examples of threading. You can use multiple objects in games like cars, motor bikes,
animals, people etc. All these objects are nothing but just threads that run your game application.
 In word processor one thread take the input from keyboard and another thread check the spelling
mistakes and third thread count the words.
 Railway ticket reservation system where multiple customers accessing the server.
 Multiple account holders accessing their accounts simultaneously on the server. When you insert a ATM
card, it starts a thread for perform your operations.
Advantages of Multithreading
 The main advantage is proper utilization or max utilization is possible.
 Decreased cost of maintenance.
 Time saving.
 Improves the performance of complex applications.
 Parallelize tasks.
Disadvantage of Multithreading
 Complex debugging and testing processes.
 Increased difficulty level in writing a program.
 Unpredictable results.
Thread Life Cycle
 During the life time of a thread, there are many states it can
enter. They include:
1. Newborn state
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
State diagram of a Thread
yield
Newborn
start
stop
stop
stop
sleep
wait
notify
Blocked
Dead
Running RunnableActive
Thread
New
Thread
Idle Thread
(Not Runnable)
Killed
Thread
Newborn
Runnable
State Dead
State
start stop
1.Newborn State
 When we create a thread object, the thread is born and is said to be in newborn state. The
thread is not yet scheduled for running. At this state, we can do only one of the following
with it:
 Schedule it for running using start() method.
 Kill it using stop() method.
2. Runnable state (start())
 The runnable state means that the thread is ready for execution and is waiting for the availability of the
processor.
 That is, the thread has joined the queue of threads that are waiting for execution.
 If all threads have equal priority, then they are given time slots for execution in round robin fashion. i.e. first-
come, first-serve manner.
3. Running
State
 Running means that the processor has given its time to the thread for its execution.
 The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread.
4. Blocked State
 A thread is said to be blocked when it is prevented form entering into the runnable state and
subsequently the running state.
 This happens when the thread is sleeping, or waiting in order to satisfy certain requirements.
 A blocked thread is considered “ not runnable” but not dead and therefore fully qualified to run again.
5. Dead State
 A running thread ends its life when is has completed executing its run() method. It is a
natural death.
 However, we can kill it by sending the stop message to it at any state thus causing a
premature death to it.
 A thread can be killed as soon it is born, or while it is running, or even when it is in “not
runnable” (blocked) condition.
Threads Methods
Thread Methods :
currentThread
start
run
stop
getName
setName
sleep
setpriority
getpriority
wait
join
isAlive
currentThread() Method
This method return complete information about the current thread like it return name of current thread, name of
group of current thread, priority number of current thread.
EXAMPLE
class Demo
{
public static void main(String args[])
{
System.out.println("current thread information is");
System.out.println(Thread.currentThread());
}
}
Output
current thread information is
Thread[main,5,main]
Current
thread
Priority
no
Group
thread
getName() Method
It is a sub method of current thread method and it return name of current thread.
EXAMPLE
class Demo
{
public static void main(String args[])
{
System.out.println("name of current thread ");
System.out.println(Thread.currentThread().getName());
}
}
output
name of current thread
main
setName() Method
It is a child method of current thread method and it is use to set name of current thread.
EXAMPLE
class Demo
{
public static void main(String args[])
{
Thread.currentThread().setName("Parent");
System.out.println("name of current thread ");
System.out.println(Thread.currentThread().getName());
}
}
Output
name of current thread
Parent
getPriority() Method
It is a child method of current thread and this method return the priority number of the current
thread.
EXAMPLE
class Demo
{
public static void main(String args[])
{
System.out.println("current thread priority ");
System.out.println(Thread.currentThread().getPriority());
}
}
Output
current thread priority
5
setPriority() Method
It is a child method of current thread method and this method is used to set the priority number of current
thread.
EXAMPLE
class Demo
{
public static void main(String args[])
{
Thread.currentThread().setPriority(9);
System.out.println("current thread priority ");
System.out.println(Thread.currentThread().getPriority());
}
}
Output
current thread priority
9
This method is used to block the current thread until the given sleep time is not complete.
Running Runnable Sleeping
sleep(t)
Sleep() Method
EXAMPLE
class Demo
{
public static void main(String
args[])
{
int i;
for(i=1;i<=5;i++)
{
System.out.println(i);
try
{
Thread.sleep(2000); //2
sec//
}
catch(Exception e)
{
}
}
}
}
Output
1
2
3
4
5
Thread Declaration
Thread can be declared in two ways :
 Create a class that extends the Thread class
 Create a class that implements the Runnable interface
1st way:
 Create a class by extending Thread class and override
run() method:
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
Create a thread:
MyThread thr1 = new MyThread();
Start Execution of threads:
thr1.start();
Create a class that implements the interface
Runnable
and override run() method:
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
Creating Object:
MyThread myObject = new MyThread();
Creating Thread Object:
Thread thr1 = new Thread( myObject );
Start Execution:
thr1.start();
2nd way:
Example of extends Thread class
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“child thread”);
}
}
}
class Demo
{
public static void main(String args[])
{
MyThread t=new MyThread();
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}
Example of implements Runnable
interface
class MyThread1 implements Runnable
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("child thread "+i);
}
}
}
class Demo
{
public static void main(String args[])
{
MyThread1 t1=new MyThread1();
Thread obj1=new Thread(t1);
obj1.start();
for(int i=0;i<5;i++)
{
System.out.println(“main thread "+i);
}
}
}
Difference between extends Thread class and implements
Runnable
 Inheritance Option: The limitation with "extends Thread" approach is that if you extend Thread, you can not
extend anything else . Java does not support multiple inheritance. In reality , you do not need Thread class
behavior , because in order to use a thread you need to instantiate one anyway.
On the other hand,
Implementing the Runnable interface gives you the choice to extend any class you like , but still define behavior
that will be run by separate thread.
 When you extends Thread class, each of your thread creates unique object and associate with it.
 When you implements Runnable, it shares the same object to multiple threads.
 When you implements Runnable, you can save a space for your class to extend any other class in future or
now.
 Another difference between Thread and Runnable comes from the fact that you are extending Thread class just
for run() method but you will get overhead of all other methods which come from Thread class. So, if your goal
is to just write some code in run() method for parallel execution then use Runnable instead of
extending Thread class.
stop() Method
This method stops a thread completely.
EXAMPLE
class Thread1 extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
if(i==2)
stop();
System.out.println("Thread1:"+i);
}
}
}
class Thread2 extends Thread
{
public void run()
{
for(int j=0;j<5;j++)
{
if(j==3)
stop();
System.out.println("Thread 2:"+j);
}
}
}
class Demo
{
public static void main(String args[])
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t1.start();
t2.start();
}
}
output
Thread 1:0
Thread 1:1
Thread 2:0
Thread 2:1
Thread 2:2
Ready/
Running
Runnable
Thread.yield
()
yield() Method
yield() method causes to pause current executing thread for giving the chance to remaining waiting threads of same
priority.
If there are no waiting threads or all waiting threads have low priority then the same thread will continue its
execution once again.
EXAMPLE
class Thread1 extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
if(i==2)
yield();
System.out.println("Thread 1:"+i);
}
System.out.println("Exit from thread1");
}
}
class Thread2 extends Thread
{
public void run()
{
for(int j=0;j<5;j++)
{
System.out.println("Thread2:“
+j);
}
System.out.println("Exit
from thread2");
}
}
class Demo
{
public static void main(String args[])
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t1.start();
t2.start();
}
}
Output
Thread 1:0
Thread 1:1
Thread 2:0
Thread 2:1
Thread 2:2
Thread 2:3
Thread 2:4
Exit from thread2
Thread 1:2
Thread 1:3
Thread 1:4
Exit from thread1
isAlive() Method
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("status :"+isAlive());
}
}
}
isAlive() method tests if the thread is alive or not and it return boolean value.
class Demo
{
public static void main(String args[])
{
MyThread t1=new MyThread();
t1.start();
System.out.println("new status
:"+t1.isAlive());
}
}
output
new status :true
status :true
status :true
status :true
status :true
status :true
join() Method
 If a thread wants to wait until completing some other thread then we should go for join
method.
 For example if a thread t1 wants to wait until completing t2 then “t1 has to call t2.join()”.
 If t1 executes t2.join() then immediately t1 will enter into waiting state until t2 completes.
 Once t2 completes then t1 will continue its execution.
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("MyThread :"+i);
}
System.out.println("Exit from my thread");
}
}
EXAMPLE WITHOUT USING JOIN
class Demo
{
public static void main(String args[])
{
MyThread t1=new MyThread();
t1.start();
for(int j=0;j<5;j++)
{
System.out.println("Main Thread :"+j);
}
System.out.println("Exit from main thread");
}
}
Output
Main Thread :0
MyThread :0
Main Thread :1
Main Thread :2
MyThread :1
Main Thread :3
MyThread :2
Main Thread :4
MyThread :3
Exit from main thread
MyThread :4
Exit from my thread
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("MyThread :"+i);
}
System.out.println("Exit from my thread");
}
}
class Demo
{
public static void main(String args[])
{
EXAMPLE USING JOIN METHOD
MyThread t1=new MyThread();
t1.start();
for(int j=0;j<5;j++)
{
try
{
t1.join();
}
catch(Exception e)
{
}
}
System.out.println("Exit from
main thread");
}
}
output
MyThread :0
MyThread :1
MyThread :2
MyThread :3
MyThread :4
Exit from my thread
Main Thread :0
Main Thread :1
Main Thread :2
Main Thread :3
Main Thread :4
Exit from main thread
Synchronization
Synchronization in java is the capability of control the access of multiple
threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread
to access the shared resource.
Why we use :
1.To prevent thread interference.
2.To prevent consistency problem.
Synchronized method is used to lock an object for any shared resource.
Example without using Synchronized
class B extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(Thread.currentThread().getName()+(i));
}
}
}
class Demo
{
public static void main(String args[])
{
B b=new B();
Thread t1=new Thread(b);
t1.setName("t1:");
t1.start();
Thread t2=new Thread(b);
t2.setName("t2:");
t2.start();
}
}
output
t1:0
t1:1
t2:0
t1:2
t2:1
t1:3
t2:2
t1:4
t2:3
t2:4
Example using Synchronized
class B extends Thread
{
public void run()
{
synchronized(this)
{
for(int i=0;i<5;i++)
{
System.out.println(Thread.current
Thread().getName()+(i));
}
}
}
}
class Demo
{
public static void main(String args[])
{
B b=new B();
Thread t1=new Thread(b);
t1.setName("t1:");
t1.start();
Thread t2=new Thread(b);
t2.setName("t2:");
t2.start();
}
}
output
t1:0
t1:1
t1:2
t1:3
t1:4
t2:0
t2:1
t2:2
t2:3
t2:4
wait() Method
 Two thread communicate each other using wait, notify and notifyAll methods.
 Wait, notify and notifyAll method are present in object class but not in thread class.
 Wait, notify and notifyAll method are called from synchronized area otherwise we get run
time exception error saying “illegal moniter state exception”
 If a thread called wait method immediately enter in waiting state but in case of notify
method it does not immediately enter in waiting state.
 Wait, notify and notifyAll methods are only method which release the lock.
Note:
Every wait method throws interrupted exception which is checked exception hence whenever
we are using wait method compulsory we should handle these interrupted exception either
by try, catch or by throws keyword otherwise we will get compile time error
if waiting state get notify function,
time complete ,if waiting thread get interrupted
If waiting thread
got lock
Ready/
Runnabl
e
Running
Waiting
State
Another
Waiting
state to
get lock
EXAMPLE
class ThreadA
{
public static void main(String args[]) throws Exception
{
ThreadB b=new ThreadB();
b.start();
synchronized(b)
{
System.out.println("main thread trying to call wait method");
b.wait();
System.out.println("main thread got notification");
System.out.println(b.total);
}
}
}
class ThreadB extends Thread
{
int total=0;
public void run()
{
synchronized(this)
{
System.out.println("child thread starts calculation");
for(int i=1;i<=100;i++)
{
total=total+i;
}
System.out.println("child thread try to give notification");
this.notify();
}
}
}
output
main thread trying to call wait method
child thread starts calculation
child thread try to give notification
main thread got notification
5050
Producer consumer problem
 Producer thread is responsible to produce items to the queue and consumer thread is responsible is
responsible to consume items to the queue.
 If queue is empty then consumer thread will call wait method and enter into waiting state.
 After producing items to the queue producer thread is responsible to call notify method then waiting
consumer will get notification and continue its execution with updated items.
class ConsumerThread
{
consume()
{
synchronized(q)
{
if(q is empty)
else
consume items
}
}
}
class ProducerThread
{
Produce()
{
synchronized(q)
{
produce items to the queue
}
}
}
Difference between notify() and
notifyAll()
 We can use notify method to give notification for only one waiting thread if multiple threads
are waiting then only one thread will be notify and remaining thread will have to wait for
further notification.
 Which thread will be notify we can’t predict it depend on JVM.
 We can use notifyAll to give the notification for all waiting threads of a particular object
even though multiple thread notify but execution will be perform one by one because threads
are require lock and only one lock is available.
Thank You

More Related Content

What's hot (20)

Interface in java
Interface in javaInterface in java
Interface in java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Java threads
Java threadsJava threads
Java threads
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
JVM
JVMJVM
JVM
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Interface
InterfaceInterface
Interface
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Java I/O
Java I/OJava I/O
Java I/O
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 

Similar to Multithreading in java

Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languagearnavytstudio2814
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javajunnubabu
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxArulmozhivarman8
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Multithreading
MultithreadingMultithreading
Multithreadingsagsharma
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptTabassumMaktum
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptTabassumMaktum
 

Similar to Multithreading in java (20)

Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Multi threading
Multi threadingMulti threading
Multi threading
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

Multithreading in java

  • 2. Process  An executing instance of a program is called process.  Also known as “Heavyweight process”.  It has own address space.  For example while writing java program in editor we can run MP3 player. At the same time we can download file from net. All these task are executing simultaneously and independent of each other. Process 1 Process 2 Process 3 Process 4 CPU
  • 3. What is Thread?  A thread is a single sequential flow of execution within a program.  A thread is a subset of process.  Thread is considered as “Light Weight Process” because it use less resource than process.  They share the address space of the process but process have their own address space.  JVM create the thread whose task is to define the main thread. Aprogram Aprogram
  • 4. A Single Threaded Program class ABC { ………. ...…….. ………. ...…….. ………. ...…….. } Beginning Single-threaded Body of Execution End
  • 5. Application Thread When we execute an application: 1. The JVM creates a Thread object whose task is defined by the main() method . 2. The JVM starts the thread . 3. The thread executes the statements of the program one by one. 4. After executing all the statements, the method returns and the thread dies.
  • 6. Difference between Process and Threads Process Thread  Process can be divided into multiple threads  Each process has its own memory space  It is difficult to create a process  Threads cannot be sub divided.  Threads of the same process share a common memory space.  It is easy to create a thread
  • 7. MULTITHREADING The process of executing multiple threads simultaneously is known as multithreading. Example  Games are very good examples of threading. You can use multiple objects in games like cars, motor bikes, animals, people etc. All these objects are nothing but just threads that run your game application.  In word processor one thread take the input from keyboard and another thread check the spelling mistakes and third thread count the words.  Railway ticket reservation system where multiple customers accessing the server.  Multiple account holders accessing their accounts simultaneously on the server. When you insert a ATM card, it starts a thread for perform your operations.
  • 8. Advantages of Multithreading  The main advantage is proper utilization or max utilization is possible.  Decreased cost of maintenance.  Time saving.  Improves the performance of complex applications.  Parallelize tasks. Disadvantage of Multithreading  Complex debugging and testing processes.  Increased difficulty level in writing a program.  Unpredictable results.
  • 9. Thread Life Cycle  During the life time of a thread, there are many states it can enter. They include: 1. Newborn state 2. Runnable State 3. Running State 4. Blocked State 5. Dead State
  • 10. State diagram of a Thread yield Newborn start stop stop stop sleep wait notify Blocked Dead Running RunnableActive Thread New Thread Idle Thread (Not Runnable) Killed Thread
  • 11. Newborn Runnable State Dead State start stop 1.Newborn State  When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following with it:  Schedule it for running using start() method.  Kill it using stop() method.
  • 12. 2. Runnable state (start())  The runnable state means that the thread is ready for execution and is waiting for the availability of the processor.  That is, the thread has joined the queue of threads that are waiting for execution.  If all threads have equal priority, then they are given time slots for execution in round robin fashion. i.e. first- come, first-serve manner. 3. Running State  Running means that the processor has given its time to the thread for its execution.  The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread. 4. Blocked State  A thread is said to be blocked when it is prevented form entering into the runnable state and subsequently the running state.  This happens when the thread is sleeping, or waiting in order to satisfy certain requirements.  A blocked thread is considered “ not runnable” but not dead and therefore fully qualified to run again.
  • 13. 5. Dead State  A running thread ends its life when is has completed executing its run() method. It is a natural death.  However, we can kill it by sending the stop message to it at any state thus causing a premature death to it.  A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable” (blocked) condition.
  • 14. Threads Methods Thread Methods : currentThread start run stop getName setName sleep setpriority getpriority wait join isAlive
  • 15. currentThread() Method This method return complete information about the current thread like it return name of current thread, name of group of current thread, priority number of current thread. EXAMPLE class Demo { public static void main(String args[]) { System.out.println("current thread information is"); System.out.println(Thread.currentThread()); } } Output current thread information is Thread[main,5,main] Current thread Priority no Group thread
  • 16. getName() Method It is a sub method of current thread method and it return name of current thread. EXAMPLE class Demo { public static void main(String args[]) { System.out.println("name of current thread "); System.out.println(Thread.currentThread().getName()); } } output name of current thread main
  • 17. setName() Method It is a child method of current thread method and it is use to set name of current thread. EXAMPLE class Demo { public static void main(String args[]) { Thread.currentThread().setName("Parent"); System.out.println("name of current thread "); System.out.println(Thread.currentThread().getName()); } } Output name of current thread Parent
  • 18. getPriority() Method It is a child method of current thread and this method return the priority number of the current thread. EXAMPLE class Demo { public static void main(String args[]) { System.out.println("current thread priority "); System.out.println(Thread.currentThread().getPriority()); } } Output current thread priority 5
  • 19. setPriority() Method It is a child method of current thread method and this method is used to set the priority number of current thread. EXAMPLE class Demo { public static void main(String args[]) { Thread.currentThread().setPriority(9); System.out.println("current thread priority "); System.out.println(Thread.currentThread().getPriority()); } } Output current thread priority 9
  • 20. This method is used to block the current thread until the given sleep time is not complete. Running Runnable Sleeping sleep(t) Sleep() Method
  • 21. EXAMPLE class Demo { public static void main(String args[]) { int i; for(i=1;i<=5;i++) { System.out.println(i); try { Thread.sleep(2000); //2 sec// } catch(Exception e) { } } } } Output 1 2 3 4 5
  • 22. Thread Declaration Thread can be declared in two ways :  Create a class that extends the Thread class  Create a class that implements the Runnable interface
  • 23. 1st way:  Create a class by extending Thread class and override run() method: class MyThread extends Thread { public void run() { // thread body of execution } } Create a thread: MyThread thr1 = new MyThread(); Start Execution of threads: thr1.start(); Create a class that implements the interface Runnable and override run() method: class MyThread implements Runnable { ..... public void run() { // thread body of execution } } Creating Object: MyThread myObject = new MyThread(); Creating Thread Object: Thread thr1 = new Thread( myObject ); Start Execution: thr1.start(); 2nd way:
  • 24. Example of extends Thread class class MyThread extends Thread { public void run() { for(int i=0;i<10;i++) { System.out.println(“child thread”); } } } class Demo { public static void main(String args[]) { MyThread t=new MyThread(); t.start(); for(int i=0;i<10;i++) { System.out.println("main thread"); } } }
  • 25.
  • 26. Example of implements Runnable interface class MyThread1 implements Runnable { public void run() { for(int i=0;i<5;i++) { System.out.println("child thread "+i); } } } class Demo { public static void main(String args[]) { MyThread1 t1=new MyThread1(); Thread obj1=new Thread(t1); obj1.start(); for(int i=0;i<5;i++) { System.out.println(“main thread "+i); } } }
  • 27.
  • 28. Difference between extends Thread class and implements Runnable  Inheritance Option: The limitation with "extends Thread" approach is that if you extend Thread, you can not extend anything else . Java does not support multiple inheritance. In reality , you do not need Thread class behavior , because in order to use a thread you need to instantiate one anyway. On the other hand, Implementing the Runnable interface gives you the choice to extend any class you like , but still define behavior that will be run by separate thread.  When you extends Thread class, each of your thread creates unique object and associate with it.  When you implements Runnable, it shares the same object to multiple threads.  When you implements Runnable, you can save a space for your class to extend any other class in future or now.  Another difference between Thread and Runnable comes from the fact that you are extending Thread class just for run() method but you will get overhead of all other methods which come from Thread class. So, if your goal is to just write some code in run() method for parallel execution then use Runnable instead of extending Thread class.
  • 29. stop() Method This method stops a thread completely. EXAMPLE class Thread1 extends Thread { public void run() { for(int i=0;i<5;i++) { if(i==2) stop(); System.out.println("Thread1:"+i); } } } class Thread2 extends Thread { public void run() { for(int j=0;j<5;j++) { if(j==3) stop(); System.out.println("Thread 2:"+j); } } } class Demo { public static void main(String args[]) { Thread1 t1=new Thread1(); Thread2 t2=new Thread2(); t1.start(); t2.start(); } } output Thread 1:0 Thread 1:1 Thread 2:0 Thread 2:1 Thread 2:2
  • 30. Ready/ Running Runnable Thread.yield () yield() Method yield() method causes to pause current executing thread for giving the chance to remaining waiting threads of same priority. If there are no waiting threads or all waiting threads have low priority then the same thread will continue its execution once again.
  • 31. EXAMPLE class Thread1 extends Thread { public void run() { for(int i=0;i<5;i++) { if(i==2) yield(); System.out.println("Thread 1:"+i); } System.out.println("Exit from thread1"); } } class Thread2 extends Thread { public void run() { for(int j=0;j<5;j++) { System.out.println("Thread2:“ +j); } System.out.println("Exit from thread2"); } } class Demo { public static void main(String args[]) { Thread1 t1=new Thread1(); Thread2 t2=new Thread2(); t1.start(); t2.start(); } }
  • 32. Output Thread 1:0 Thread 1:1 Thread 2:0 Thread 2:1 Thread 2:2 Thread 2:3 Thread 2:4 Exit from thread2 Thread 1:2 Thread 1:3 Thread 1:4 Exit from thread1
  • 33. isAlive() Method class MyThread extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println("status :"+isAlive()); } } } isAlive() method tests if the thread is alive or not and it return boolean value. class Demo { public static void main(String args[]) { MyThread t1=new MyThread(); t1.start(); System.out.println("new status :"+t1.isAlive()); } } output new status :true status :true status :true status :true status :true status :true
  • 34. join() Method  If a thread wants to wait until completing some other thread then we should go for join method.  For example if a thread t1 wants to wait until completing t2 then “t1 has to call t2.join()”.  If t1 executes t2.join() then immediately t1 will enter into waiting state until t2 completes.  Once t2 completes then t1 will continue its execution.
  • 35. class MyThread extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println("MyThread :"+i); } System.out.println("Exit from my thread"); } } EXAMPLE WITHOUT USING JOIN class Demo { public static void main(String args[]) { MyThread t1=new MyThread(); t1.start(); for(int j=0;j<5;j++) { System.out.println("Main Thread :"+j); } System.out.println("Exit from main thread"); } }
  • 36. Output Main Thread :0 MyThread :0 Main Thread :1 Main Thread :2 MyThread :1 Main Thread :3 MyThread :2 Main Thread :4 MyThread :3 Exit from main thread MyThread :4 Exit from my thread
  • 37. class MyThread extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println("MyThread :"+i); } System.out.println("Exit from my thread"); } } class Demo { public static void main(String args[]) { EXAMPLE USING JOIN METHOD MyThread t1=new MyThread(); t1.start(); for(int j=0;j<5;j++) { try { t1.join(); } catch(Exception e) { } } System.out.println("Exit from main thread"); } }
  • 38. output MyThread :0 MyThread :1 MyThread :2 MyThread :3 MyThread :4 Exit from my thread Main Thread :0 Main Thread :1 Main Thread :2 Main Thread :3 Main Thread :4 Exit from main thread
  • 39. Synchronization Synchronization in java is the capability of control the access of multiple threads to any shared resource. Java Synchronization is better option where we want to allow only one thread to access the shared resource. Why we use : 1.To prevent thread interference. 2.To prevent consistency problem. Synchronized method is used to lock an object for any shared resource.
  • 40. Example without using Synchronized class B extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println(Thread.currentThread().getName()+(i)); } } } class Demo { public static void main(String args[]) { B b=new B(); Thread t1=new Thread(b); t1.setName("t1:"); t1.start(); Thread t2=new Thread(b); t2.setName("t2:"); t2.start(); } }
  • 42. Example using Synchronized class B extends Thread { public void run() { synchronized(this) { for(int i=0;i<5;i++) { System.out.println(Thread.current Thread().getName()+(i)); } } } } class Demo { public static void main(String args[]) { B b=new B(); Thread t1=new Thread(b); t1.setName("t1:"); t1.start(); Thread t2=new Thread(b); t2.setName("t2:"); t2.start(); } }
  • 44. wait() Method  Two thread communicate each other using wait, notify and notifyAll methods.  Wait, notify and notifyAll method are present in object class but not in thread class.  Wait, notify and notifyAll method are called from synchronized area otherwise we get run time exception error saying “illegal moniter state exception”  If a thread called wait method immediately enter in waiting state but in case of notify method it does not immediately enter in waiting state.  Wait, notify and notifyAll methods are only method which release the lock. Note: Every wait method throws interrupted exception which is checked exception hence whenever we are using wait method compulsory we should handle these interrupted exception either by try, catch or by throws keyword otherwise we will get compile time error
  • 45. if waiting state get notify function, time complete ,if waiting thread get interrupted If waiting thread got lock Ready/ Runnabl e Running Waiting State Another Waiting state to get lock
  • 46. EXAMPLE class ThreadA { public static void main(String args[]) throws Exception { ThreadB b=new ThreadB(); b.start(); synchronized(b) { System.out.println("main thread trying to call wait method"); b.wait(); System.out.println("main thread got notification"); System.out.println(b.total); } } }
  • 47. class ThreadB extends Thread { int total=0; public void run() { synchronized(this) { System.out.println("child thread starts calculation"); for(int i=1;i<=100;i++) { total=total+i; } System.out.println("child thread try to give notification"); this.notify(); } } } output main thread trying to call wait method child thread starts calculation child thread try to give notification main thread got notification 5050
  • 48. Producer consumer problem  Producer thread is responsible to produce items to the queue and consumer thread is responsible is responsible to consume items to the queue.  If queue is empty then consumer thread will call wait method and enter into waiting state.  After producing items to the queue producer thread is responsible to call notify method then waiting consumer will get notification and continue its execution with updated items. class ConsumerThread { consume() { synchronized(q) { if(q is empty) else consume items } } } class ProducerThread { Produce() { synchronized(q) { produce items to the queue } } }
  • 49. Difference between notify() and notifyAll()  We can use notify method to give notification for only one waiting thread if multiple threads are waiting then only one thread will be notify and remaining thread will have to wait for further notification.  Which thread will be notify we can’t predict it depend on JVM.  We can use notifyAll to give the notification for all waiting threads of a particular object even though multiple thread notify but execution will be perform one by one because threads are require lock and only one lock is available.