SlideShare a Scribd company logo
MULTITHREADING
BY LECTURER SURAJ PANDEY CCT COLLEGE
Multithreading in java
Multithreading in java is a process of executing multiple
threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit
of processing. Multiprocessing and multithreading, both are
used to achieve multitasking.
But we use multithreading than multiprocessing because
threads share a common memory area. They don't allocate
separate memory area so saves memory, and context-
switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Advantage of Java Multithreading
1) It doesn't block the user because threads are
independent and you can perform multiple operations at
same time.
2) You can perform many operations together so it
saves time.
3) Threads are independent so it doesn't affect other threads
if exception occur in a single thread.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Multitasking
Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
BY LECTURER SURAJ PANDEY CCT COLLEGE
1) Process-based Multitasking (Multiprocessing)
Each process have its own address in memory i.e. each
process allocates separate memory area.
Process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another require some time for
saving and loading registers, memory maps, updating lists
etc.
BY LECTURER SURAJ PANDEY CCT COLLEGE
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.
BY LECTURER SURAJ PANDEY CCT COLLEGE
What is Thread in java
A thread is a lightweight sub process, a smallest unit of
processing. It is a separate path of execution.
Threads are independent, if there occurs exception in one
thread, it doesn't affect other threads. It shares a common
memory area.
BY LECTURER SURAJ PANDEY CCT COLLEGE
BY LECTURER SURAJ PANDEY CCT COLLEGE
As shown in the above figure, thread is executed inside the
process. There is context-switching between the threads.
There can be multiple processes inside the OS and one
process can have multiple threads.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Life cycle of a Thread (Thread States)
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
a thread is always in one of these five states. It can move from
one state to another via a variety of ways as shown in fig.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Newborn
Running Runnable
Blocked
Dead
Start
Stop
Stop
Stop
resume
notify
suspend
sleep wait
Idle
Thread(notR
unnable)
New
Thread
Active
Thread
yield
Killed
Thread
State transition diagram of a thread
BY LECTURER SURAJ PANDEY CCT COLLEGE
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 schedule for running. At this
state, we can do only one of the following things with it:
Schedule it for running using start() method.
Kill it using stop() method
If scheduled, it moves to the runnable state . If we attempt to use any other
method at this stage, an exception will be thrown.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Runnable State:
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. The thread that relinquishes control joins the queue at the
end and again waits for its turn. This process of assigning time to
threads is known as time-slicing.
However, if we want a thread to relinquish control, to another
thread to equal priority before its turn comes, we can do so by
using the yield() method
BY LECTURER SURAJ PANDEY CCT COLLEGE
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 its preempted by a higher priority thread. A running thread
may relinquish its control in one of the following situations.
It has been suspended using suspend() method. A suspended thread can be
revived by using the resume() method. This approach is useful when we want
to suspend a thread for some time due to certain reason, but do not want to
kill it.
It has been made to sleep, we can put a thread to sleep for a specific time
period using the method sleep(time) where time is milliseconds. This means
that the thread is out of the queue during this time period. The thread re-
enters the runnable state as soon as this time period is elapsed.
BY LECTURER SURAJ PANDEY CCT COLLEGE
It has been told to wait until some event occurs. This is done
using the wait() method. The thread can be scheduled to run
again using the notify() method.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Blocked state:
A thread is said to be blocked when it is prevented from entering
into the runnable state and subsequently the running state. This
happens when the thread is suspended, 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.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Dead state:
Every thread has a life cycle. A running thread ends its life when it
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 this 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.
BY LECTURER SURAJ PANDEY CCT COLLEGE
How to create thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and
perform operations on a thread.Thread class extends Object
class and implements Runnable interface.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Commonly used methods of Thread class:
 public void run(): is used to perform action for a thread.
 public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
 public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
 public void join(): waits for a thread to die.
 public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
 public int getPriority(): returns the priority of the thread.
 public int setPriority(int priority): changes the priority of the thread.
 public String getName(): returns the name of the thread.
 public void setName(String name): changes the name of the thread.
 public Thread currentThread(): returns the reference of currently executing
thread.
 public int getId(): returns the id of the thread.
 public Thread.State getState(): returns the state of the thread.
BY LECTURER SURAJ PANDEY CCT COLLEGE
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread
object to temporarily pause and allow other threads to execute.
public void suspend(): is used to suspend the
thread(depricated).
public void resume(): is used to resume the suspended
thread(depricated).
public void stop(): is used to stop the thread(depricated).
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been
interrupted.
public static boolean interrupted(): tests if the current
thread has been interrupted.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Runnable interface:
The Runnable interface should be implemented by any class
whose instances are intended to be executed by a thread.
Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly
created thread. It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run()
method will run.
BY LECTURER SURAJ PANDEY CCT COLLEGE
1)By extending Thread class
class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
}  
BY LECTURER SURAJ PANDEY CCT COLLEGE
2)By implementing the Runnable
interface
class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
 }  
}  
BY LECTURER SURAJ PANDEY CCT COLLEGE
Thread Scheduler in Java
Thread scheduler in java is the part of the JVM that
decides which thread should run.
There is no guarantee that which runnable thread will be
chosen to run by the thread scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing
scheduling to schedule the threads.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Sleep method in java
The sleep() method of Thread class is used to sleep a thread
for the specified amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a
thread:
public static void sleep(long miliseconds)throws
InterruptedException
public static void sleep(long miliseconds, int
nanos)throws InterruptedException
BY LECTURER SURAJ PANDEY CCT COLLEGE
Example of sleep method in java
 class TestSleepMethod1 extends Thread{  
 public void run(){  
  for(int i=1;i<5;i++){  
    try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
    System.out.println(i);  
  }  
 }  
 public static void main(String args[]){  
  TestSleepMethod1 t1=new TestSleepMethod1();  
  TestSleepMethod1 t2=new TestSleepMethod1();     
t1.start();  
  t2.start();  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT COLLEGE
Output:
 1
 1
 2
 2
 3
3
 4
 4
BY LECTURER SURAJ PANDEY CCT COLLEGE
The join() method:
The join() method waits for a thread to die. In other words,
it causes the currently running threads to stop executing
until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws
InterruptedException
BY LECTURER SURAJ PANDEY CCT COLLEGE
Example of join() method
BY LECTURER SURAJ PANDEY CCT COLLEGE
BY LECTURER SURAJ PANDEY CCT COLLEGE
class TestJoinMethod1 extends Thread{  
 public void run(){  
  for(int i=1;i<=5;i++){  
   try{  
    Thread.sleep(500);  
   }catch(Exception e)
{
System.out.println(e);}  
  System.out.println(i);  
  }  
 }  
public static void main(String args[]){  
 TestJoinMethod1 t1=new TestJoinMethod1();  
 TestJoinMethod1 t2=new TestJoinMethod1();  
 TestJoinMethod1 t3=new TestJoinMethod1();  
 t1.start();  
 try{  
  t1.join();  
 }catch(Exception e){System.out.println(e);}  
  
 t2.start();  
 t3.start();  
 }  
}  
 Output:1
 2
 3
 4
 5
 1
 1
 2
 2
 3
 3
 4
 4
 5
 5
  BY LECTURER SURAJ PANDEY CCT COLLEGE
As you can see in the above example,when t1 completes its
task then t2 and t3 starts executing.
BY LECTURER SURAJ PANDEY CCT COLLEGE
getName(),setName(String) and getId() method:
BY LECTURER SURAJ PANDEY CCT COLLEGE
 class TestJoinMethod3 extends Thread{  
  public void run(){  
   System.out.println("running...");  
  }  
 public static void main(String args[]){  
  TestJoinMethod3 t1=new TestJoinMethod3();  
  TestJoinMethod3 t2=new TestJoinMethod3();  
  System.out.println("Name of t1:"+t1.getName());  
  System.out.println("Name of t2:"+t2.getName());  
  System.out.println("id of t1:"+t1.getId());    
  t1.start();  
  t2.start();    
  t1.setName(“Ravi");  
  System.out.println("After changing name of t1:"+t1.getName());  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT COLLEGE
Output:Name of t1:Thread-0
 Name of t2:Thread-1
 id of t1:8
 running...
 After changling name of t1:Ravi
 running...

BY LECTURER SURAJ PANDEY CCT COLLEGE
The currentThread() method:
The currentThread() method returns a reference to the
currently executing thread object.
Syntax:
public static Thread currentThread()
BY LECTURER SURAJ PANDEY CCT COLLEGE
Example of currentThread() method
class TestJoinMethod4 extends Thread
 {  
 public void run(){  
  System.out.println(Thread.currentThread().getName());  
 }  
 }  
 public static void main(String args[]){  
  TestJoinMethod4 t1=new TestJoinMethod4();  
  TestJoinMethod4 t2=new TestJoinMethod4();    
t1.start();  
  t2.start();  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT COLLEGE
Output:Thread-0
 Thread-1
BY LECTURER SURAJ PANDEY CCT COLLEGE
Naming a thread:
The Thread class provides methods to change and get the
name of a thread.
public String getName(): is used to return the name of a
thread.
public void setName(String name): is used to change
the name of a thread.
BY LECTURER SURAJ PANDEY CCT COLLEGE
class TestMultiNaming1 extends Thread{  
public void run(){  
   System.out.println("running...");  
  }  
 public static void main(String args[]){  
  TestMultiNaming1 t1=new TestMultiNaming1();  
  TestMultiNaming1 t2=new TestMultiNaming1();  
  System.out.println("Name of t1:"+t1.getName());  
  System.out.println("Name of t2:"+t2.getName());     
t1.start();  
  t2.start();    
 t1.setName("Sonoo Jaiswal");  
  System.out.println("After changing name of t1:"+t1.getName());  
 }  
}  
BY LECTURER SURAJ PANDEY CCT COLLEGE
Output:
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
BY LECTURER SURAJ PANDEY CCT COLLEGE
Thread priority
Each thread have a priority. Priorities are represented by a
number between 1 and 10. In most cases, thread schedular
schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it
depends on JVM specification that which scheduling it
chooses
BY LECTURER SURAJ PANDEY CCT COLLEGE
3 constants defiend in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The
value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Example of priority of a Thread:
BY LECTURER SURAJ PANDEY CCT COLLEGE
 class TestMultiPriority1 extends Thread{  
 public void run(){  
   System.out.println("running thread name is:"+Thread.currentThread().getName());  
   System.out.println("running thread priority is:"+Thread.currentThread().getPriority());  
  }  
 public static void main(String args[]){  
  TestMultiPriority1 m1=new TestMultiPriority1();  
  TestMultiPriority1 m2=new TestMultiPriority1();  
  m1.setPriority(Thread.MIN_PRIORITY);  
  m2.setPriority(Thread.MAX_PRIORITY);  
  m1.start();  
  m2.start();     
 }  
}     
BY LECTURER SURAJ PANDEY CCT COLLEGE
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
BY LECTURER SURAJ PANDEY CCT COLLEGE
Thread synchronization
When two or more threads need access to a shared resource,
they need some way to ensure that the resource will be used by
only one thread at a time. The process by which the thread is
achieved is called synchronization.
The keyword synchronized helps to solve such problems by
keeping a watch on such locations. For example, the method that
will read information from a file and the method that will update
the same file may be declared as synchronized.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Why use Synchronization
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem
BY LECTURER SURAJ PANDEY CCT COLLEGE
Thread Synchronization
There are two types of thread synchronization mutual
exclusive and inter-thread communication.
Mutual Exclusive
Synchronized method.
Synchronized block.
static synchronization.
Cooperation (Inter-thread communication in java)
BY LECTURER SURAJ PANDEY CCT COLLEGE
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with
one another while sharing data. This can be done by three
ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
BY LECTURER SURAJ PANDEY CCT COLLEGE
synchronized void update()
{
…………….
……………. // code here is synchronized
…………….
}
when we declare a method synchronized, java creates a
“monitor” and hands it over to the thread that calls the method
first time. As long as the thread holds the monitor, no other
thread can enter the synchronized section of code. A monitor is
like a key and the thread that holds the key can only open the
lock.
BY LECTURER SURAJ PANDEY CCT COLLEGE
It is also possible to mark a block of code as synchronized as
shown below:
synchronized (lock-object)
{
………………..
………………. // code here is synchronized
}
Whenever a thread has completed its work of using synchronized
method (or block of code), it will hand over the monitor to the
next thread that is ready to use the same resource.
BY LECTURER SURAJ PANDEY CCT COLLEGE
An interesting situation may occur when two or more threads are
waiting to gain control of a resource. Due to some reasons, the
condition on which the waiting threads rely on to gain control does not
happen. This result in what is known as deadlock. For example, assume
that the thread A must access Method1 before it can release
Method2. because these are mutually exclusive conditions, a deadlock
occurs. The code below illustrate this.
 Thread A
synchronized method2()
{
synchronized method1()
{
………………..
………………..
}
}
BY LECTURER SURAJ PANDEY CCT COLLEGE
Thread B
synchronized method1()
{
synchronized method2()
{
………………..
………………..
}
}
BY LECTURER SURAJ PANDEY CCT COLLEGE
Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can
occur in a situation when a thread is waiting for an object
lock, that is acquired by another thread and second thread is
waiting for an object lock that is acquired by first thread.
Since, both threads are waiting for each other to release the
lock, the condition is called deadlock
BY LECTURER SURAJ PANDEY CCT COLLEGE
BY LECTURER SURAJ PANDEY CCT COLLEGE
Inter-thread communication in Java
Inter-thread communication or Co-operation is all
about allowing synchronized threads to communicate with
each other.
Cooperation (Inter-thread communication) is a mechanism
in which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by
following methods of Object class:
1. wait()
2. notify()
3. notifyAll()
BY LECTURER SURAJ PANDEY CCT COLLEGE
1) wait() method
Causes current thread to release the lock and wait until
either another thread invokes the notify() method or the
notifyAll() method for this object, or a specified amount of
time has elapsed.
The current thread must own this object's monitor, so it
must be called from the synchronized method only otherwise
it will throw exception.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Method Description
public final void
wait()throws
InterruptedException
public final void wait(long
timeout)throws
InterruptedException
waits until object is
notified
waits for the specified
amount of time
BY LECTURER SURAJ PANDEY CCT COLLEGE
2) notify() method
Wakes up a single thread that is waiting on this object's
monitor. If any threads are waiting on this object, one of
them is chosen to be awakened. The choice is arbitrary and
occurs at the discretion of the implementation. Syntax:
public final void notify()
BY LECTURER SURAJ PANDEY CCT COLLEGE
3) notifyAll() method
Wakes up all threads that are waiting on this object's
monitor. Syntax:
public final void notifyAll()
BY LECTURER SURAJ PANDEY CCT COLLEGE

More Related Content

PPTX
PPT
Exception Handling in JAVA
PPTX
Constructor in java
PPT
Java Threads
PPT
9. Input Output in java
ODP
Multithreading In Java
PDF
Java - File Input Output Concepts
PPTX
Strings in Java
Exception Handling in JAVA
Constructor in java
Java Threads
9. Input Output in java
Multithreading In Java
Java - File Input Output Concepts
Strings in Java

What's hot (20)

PPTX
java interface and packages
PPTX
Multithreading in java
PPTX
MULTI THREADING IN JAVA
PPTX
L22 multi-threading-introduction
PPTX
Static keyword ppt
PPTX
Packages in java
PPTX
Type casting in java
PPS
String and string buffer
PPTX
Inheritance in JAVA PPT
PPT
Synchronization.37
PDF
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
PDF
Java I/o streams
PPTX
WHAT IS ABSTRACTION IN JAVA
PPTX
Methods in java
PPTX
Multi threading
PPS
Wrapper class
PDF
Polymorphism In Java
PPTX
Classes objects in java
PPTX
Multithreading in java
PPTX
Classes, objects in JAVA
java interface and packages
Multithreading in java
MULTI THREADING IN JAVA
L22 multi-threading-introduction
Static keyword ppt
Packages in java
Type casting in java
String and string buffer
Inheritance in JAVA PPT
Synchronization.37
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java I/o streams
WHAT IS ABSTRACTION IN JAVA
Methods in java
Multi threading
Wrapper class
Polymorphism In Java
Classes objects in java
Multithreading in java
Classes, objects in JAVA
Ad

Similar to Basic of Multithreading in JAva (20)

PPT
Java And Multithreading
PPTX
Slide 7 Thread-1.pptx
PPTX
Concept of Java Multithreading-Partially.pptx
PPTX
unit3multithreadingppt-copy-180122162204.pptx
PPTX
unit3 Exception Handling multithreadingppt.pptx
PPTX
Multithreading in Java Object Oriented Programming language
PPTX
Multi threading
PPTX
Threads in Java
PPTX
MSBTE Computer Engineering JPR java. multi. threading.pptx
PPTX
multithreading,thread and processinjava-210302183809.pptx
PDF
Java Multithreading Interview Questions PDF By ScholarHat
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
PDF
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
PPTX
econtent thread in java.pptx
PDF
Multithreading Introduction and Lifecyle of thread
PPTX
Multithreading in java
PPTX
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
PPTX
JAVA THEORY PPT.pptx on based up on the transaction
PDF
Unit-3 MULTITHREADING-2.pdf
PPT
Thread model in java
Java And Multithreading
Slide 7 Thread-1.pptx
Concept of Java Multithreading-Partially.pptx
unit3multithreadingppt-copy-180122162204.pptx
unit3 Exception Handling multithreadingppt.pptx
Multithreading in Java Object Oriented Programming language
Multi threading
Threads in Java
MSBTE Computer Engineering JPR java. multi. threading.pptx
multithreading,thread and processinjava-210302183809.pptx
Java Multithreading Interview Questions PDF By ScholarHat
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
econtent thread in java.pptx
Multithreading Introduction and Lifecyle of thread
Multithreading in java
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
JAVA THEORY PPT.pptx on based up on the transaction
Unit-3 MULTITHREADING-2.pdf
Thread model in java
Ad

More from suraj pandey (20)

PPT
Systemcare in computer
PPT
vb.net Constructor and destructor
PPTX
Overloading and overriding in vb.net
PPT
Basic in Computernetwork
PPT
Computer hardware
PPT
Dos commands new
PPT
History of computer
PPT
Dos commands
PPT
Basic of Internet&email
PPT
Basic fundamental Computer input/output Accessories
PPT
Introduction of exception in vb.net
PPT
Transmission mediums in computer networks
PPTX
Introduction to vb.net
PPT
Introduction to computer
PPT
Computer Fundamental Network topologies
PPTX
Basic of Computer software
PPT
Basic using of Swing in Java
PPT
Basic Networking in Java
PPT
Basic Java Database Connectivity(JDBC)
PPT
Graphical User Interface in JAVA
Systemcare in computer
vb.net Constructor and destructor
Overloading and overriding in vb.net
Basic in Computernetwork
Computer hardware
Dos commands new
History of computer
Dos commands
Basic of Internet&email
Basic fundamental Computer input/output Accessories
Introduction of exception in vb.net
Transmission mediums in computer networks
Introduction to vb.net
Introduction to computer
Computer Fundamental Network topologies
Basic of Computer software
Basic using of Swing in Java
Basic Networking in Java
Basic Java Database Connectivity(JDBC)
Graphical User Interface in JAVA

Recently uploaded (20)

PDF
Computing-Curriculum for Schools in Ghana
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
RMMM.pdf make it easy to upload and study
PPTX
Cell Types and Its function , kingdom of life
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Computing-Curriculum for Schools in Ghana
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Module 4: Burden of Disease Tutorial Slides S2 2025
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
RMMM.pdf make it easy to upload and study
Cell Types and Its function , kingdom of life
O7-L3 Supply Chain Operations - ICLT Program
Supply Chain Operations Speaking Notes -ICLT Program
Anesthesia in Laparoscopic Surgery in India
O5-L3 Freight Transport Ops (International) V1.pdf
Complications of Minimal Access Surgery at WLH
Final Presentation General Medicine 03-08-2024.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
VCE English Exam - Section C Student Revision Booklet
Yogi Goddess Pres Conference Studio Updates
A systematic review of self-coping strategies used by university students to ...
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Final Presentation General Medicine 03-08-2024.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf

Basic of Multithreading in JAva

  • 1. MULTITHREADING BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 2. Multithreading in java Multithreading in java is a process of executing multiple threads simultaneously. Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context- switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation etc. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 3. Advantage of Java Multithreading 1) It doesn't block the user because threads are independent and you can perform multiple operations at same time. 2) You can perform many operations together so it saves time. 3) Threads are independent so it doesn't affect other threads if exception occur in a single thread. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 4. Multitasking Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways: 1. Process-based Multitasking(Multiprocessing) 2. Thread-based Multitasking(Multithreading) BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 5. 1) Process-based Multitasking (Multiprocessing) Each process have its own address in memory i.e. each process allocates separate memory area. Process is heavyweight. Cost of communication between the process is high. Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 6. 2) Thread-based Multitasking (Multithreading) Threads share the same address space. Thread is lightweight. Cost of communication between the thread is low. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 7. What is Thread in java A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution. Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 8. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 9. As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 10. Life cycle of a Thread (Thread States) 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 a thread is always in one of these five states. It can move from one state to another via a variety of ways as shown in fig. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 12. 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 schedule for running. At this state, we can do only one of the following things with it: Schedule it for running using start() method. Kill it using stop() method If scheduled, it moves to the runnable state . If we attempt to use any other method at this stage, an exception will be thrown. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 13. Runnable State: 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. The thread that relinquishes control joins the queue at the end and again waits for its turn. This process of assigning time to threads is known as time-slicing. However, if we want a thread to relinquish control, to another thread to equal priority before its turn comes, we can do so by using the yield() method BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 14. 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 its preempted by a higher priority thread. A running thread may relinquish its control in one of the following situations. It has been suspended using suspend() method. A suspended thread can be revived by using the resume() method. This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it. It has been made to sleep, we can put a thread to sleep for a specific time period using the method sleep(time) where time is milliseconds. This means that the thread is out of the queue during this time period. The thread re- enters the runnable state as soon as this time period is elapsed. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 15. It has been told to wait until some event occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 16. Blocked state: A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, 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. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 17. Dead state: Every thread has a life cycle. A running thread ends its life when it 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 this 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. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 18. How to create thread There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface. Thread class: Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 19. Commonly used methods of Thread class:  public void run(): is used to perform action for a thread.  public void start(): starts the execution of the thread.JVM calls the run() method on the thread.  public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.  public void join(): waits for a thread to die.  public void join(long miliseconds): waits for a thread to die for the specified miliseconds.  public int getPriority(): returns the priority of the thread.  public int setPriority(int priority): changes the priority of the thread.  public String getName(): returns the name of the thread.  public void setName(String name): changes the name of the thread.  public Thread currentThread(): returns the reference of currently executing thread.  public int getId(): returns the id of the thread.  public Thread.State getState(): returns the state of the thread. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 20. public boolean isAlive(): tests if the thread is alive. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. public void suspend(): is used to suspend the thread(depricated). public void resume(): is used to resume the suspended thread(depricated). public void stop(): is used to stop the thread(depricated). public void interrupt(): interrupts the thread. public boolean isInterrupted(): tests if the thread has been interrupted. public static boolean interrupted(): tests if the current thread has been interrupted. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 21. Runnable interface: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). public void run(): is used to perform action for a thread. Starting a thread: start() method of Thread class is used to start a newly created thread. It performs following tasks: A new thread starts(with new callstack). The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run() method will run. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 22. 1)By extending Thread class class Multi extends Thread{   public void run(){   System.out.println("thread is running...");   }   public static void main(String args[]){   Multi t1=new Multi();   t1.start();    }   }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 23. 2)By implementing the Runnable interface class Multi3 implements Runnable{   public void run(){   System.out.println("thread is running...");   }   public static void main(String args[]){   Multi3 m1=new Multi3();   Thread t1 =new Thread(m1);   t1.start();    }   }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 24. Thread Scheduler in Java Thread scheduler in java is the part of the JVM that decides which thread should run. There is no guarantee that which runnable thread will be chosen to run by the thread scheduler. Only one thread at a time can run in a single process. The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 25. Sleep method in java The sleep() method of Thread class is used to sleep a thread for the specified amount of time. Syntax of sleep() method in java The Thread class provides two methods for sleeping a thread: public static void sleep(long miliseconds)throws InterruptedException public static void sleep(long miliseconds, int nanos)throws InterruptedException BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 26. Example of sleep method in java  class TestSleepMethod1 extends Thread{    public void run(){     for(int i=1;i<5;i++){       try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}       System.out.println(i);     }    }    public static void main(String args[]){     TestSleepMethod1 t1=new TestSleepMethod1();     TestSleepMethod1 t2=new TestSleepMethod1();      t1.start();     t2.start();    }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 27. Output:  1  1  2  2  3 3  4  4 BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 28. The join() method: The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. Syntax: public void join()throws InterruptedException public void join(long milliseconds)throws InterruptedException BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 29. Example of join() method BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 30. BY LECTURER SURAJ PANDEY CCT COLLEGE class TestJoinMethod1 extends Thread{    public void run(){     for(int i=1;i<=5;i++){      try{       Thread.sleep(500);      }catch(Exception e) { System.out.println(e);}     System.out.println(i);     }    }   public static void main(String args[]){    TestJoinMethod1 t1=new TestJoinMethod1();    TestJoinMethod1 t2=new TestJoinMethod1();    TestJoinMethod1 t3=new TestJoinMethod1();    t1.start();    try{     t1.join();    }catch(Exception e){System.out.println(e);}       t2.start();    t3.start();    }   }  
  • 31.  Output:1  2  3  4  5  1  1  2  2  3  3  4  4  5  5   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 32. As you can see in the above example,when t1 completes its task then t2 and t3 starts executing. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 33. getName(),setName(String) and getId() method: BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 35. Output:Name of t1:Thread-0  Name of t2:Thread-1  id of t1:8  running...  After changling name of t1:Ravi  running...  BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 36. The currentThread() method: The currentThread() method returns a reference to the currently executing thread object. Syntax: public static Thread currentThread() BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 37. Example of currentThread() method class TestJoinMethod4 extends Thread  {    public void run(){     System.out.println(Thread.currentThread().getName());    }    }    public static void main(String args[]){     TestJoinMethod4 t1=new TestJoinMethod4();     TestJoinMethod4 t2=new TestJoinMethod4();     t1.start();     t2.start();    }    }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 39. Naming a thread: The Thread class provides methods to change and get the name of a thread. public String getName(): is used to return the name of a thread. public void setName(String name): is used to change the name of a thread. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 41. Output: Name of t1:Thread-0 Name of t2:Thread-1 id of t1:8 running... BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 42. Thread priority Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 43. 3 constants defiend in Thread class: 1. public static int MIN_PRIORITY 2. public static int NORM_PRIORITY 3. public static int MAX_PRIORITY Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 44. Example of priority of a Thread: BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 46. Output: running thread name is:Thread-0 running thread priority is:10 running thread name is:Thread-1 running thread priority is:1 BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 47. Thread synchronization When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which the thread is achieved is called synchronization. The keyword synchronized helps to solve such problems by keeping a watch on such locations. For example, the method that will read information from a file and the method that will update the same file may be declared as synchronized. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 48. Why use Synchronization The synchronization is mainly used to 1. To prevent thread interference. 2. To prevent consistency problem BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 49. Thread Synchronization There are two types of thread synchronization mutual exclusive and inter-thread communication. Mutual Exclusive Synchronized method. Synchronized block. static synchronization. Cooperation (Inter-thread communication in java) BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 50. Mutual Exclusive Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java: 1. by synchronized method 2. by synchronized block 3. by static synchronization BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 51. synchronized void update() { ……………. ……………. // code here is synchronized ……………. } when we declare a method synchronized, java creates a “monitor” and hands it over to the thread that calls the method first time. As long as the thread holds the monitor, no other thread can enter the synchronized section of code. A monitor is like a key and the thread that holds the key can only open the lock. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 52. It is also possible to mark a block of code as synchronized as shown below: synchronized (lock-object) { ……………….. ………………. // code here is synchronized } Whenever a thread has completed its work of using synchronized method (or block of code), it will hand over the monitor to the next thread that is ready to use the same resource. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 53. An interesting situation may occur when two or more threads are waiting to gain control of a resource. Due to some reasons, the condition on which the waiting threads rely on to gain control does not happen. This result in what is known as deadlock. For example, assume that the thread A must access Method1 before it can release Method2. because these are mutually exclusive conditions, a deadlock occurs. The code below illustrate this.  Thread A synchronized method2() { synchronized method1() { ……………….. ……………….. } } BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 54. Thread B synchronized method1() { synchronized method2() { ……………….. ……………….. } } BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 55. Deadlock in java Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 56. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 57. Inter-thread communication in Java Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class: 1. wait() 2. notify() 3. notifyAll() BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 58. 1) wait() method Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 59. Method Description public final void wait()throws InterruptedException public final void wait(long timeout)throws InterruptedException waits until object is notified waits for the specified amount of time BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 60. 2) notify() method Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax: public final void notify() BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 61. 3) notifyAll() method Wakes up all threads that are waiting on this object's monitor. Syntax: public final void notifyAll() BY LECTURER SURAJ PANDEY CCT COLLEGE