SlideShare uma empresa Scribd logo
1 de 61
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

Mais conteúdo relacionado

Mais procurados

Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
myrajendra
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
APU
 

Mais procurados (20)

Java threads
Java threadsJava threads
Java threads
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
 
Thread
ThreadThread
Thread
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
Java Virtual Machine (JVM), Difference JDK, JRE & JVMJava Virtual Machine (JVM), Difference JDK, JRE & JVM
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Java Garbage Collection - How it works
Java Garbage Collection - How it worksJava Garbage Collection - How it works
Java Garbage Collection - How it works
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 

Semelhante a Basic of Multithreading in JAva

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
arnavytstudio2814
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
JAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transactionJAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transaction
SaikiranBiradar3
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
HKShab
 

Semelhante a Basic of Multithreading in JAva (20)

Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
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
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
JAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transactionJAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transaction
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
Java threading
Java threadingJava threading
Java threading
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
The Concept Of Multithreading In Java Programming
The Concept Of Multithreading In Java ProgrammingThe Concept Of Multithreading In Java Programming
The Concept Of Multithreading In Java Programming
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Mais de suraj pandey

Mais de suraj pandey (20)

Systemcare in computer
Systemcare in computer Systemcare in computer
Systemcare in computer
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructor
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
 
Basic in Computernetwork
Basic in ComputernetworkBasic in Computernetwork
Basic in Computernetwork
 
Computer hardware
Computer hardwareComputer hardware
Computer hardware
 
Dos commands new
Dos commands new Dos commands new
Dos commands new
 
History of computer
History of computerHistory of computer
History of computer
 
Dos commands
Dos commandsDos commands
Dos commands
 
Basic of Internet&email
Basic of Internet&emailBasic of Internet&email
Basic of Internet&email
 
Basic fundamental Computer input/output Accessories
Basic fundamental Computer input/output AccessoriesBasic fundamental Computer input/output Accessories
Basic fundamental Computer input/output Accessories
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.net
 
Transmission mediums in computer networks
Transmission mediums in computer networksTransmission mediums in computer networks
Transmission mediums in computer networks
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.net
 
Introduction to computer
Introduction to computerIntroduction to computer
Introduction to computer
 
Computer Fundamental Network topologies
Computer Fundamental Network topologiesComputer Fundamental Network topologies
Computer Fundamental Network topologies
 
Basic of Computer software
Basic of Computer softwareBasic of Computer software
Basic of Computer software
 
Basic using of Swing in Java
Basic using of Swing in JavaBasic using of Swing in Java
Basic using of Swing in Java
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVA
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Último (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
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
 

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