[go: up one dir, main page]

0% found this document useful (0 votes)
13 views58 pages

Unit-1 Topic 1.4 - Muthithreading - U

nice

Uploaded by

pappu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views58 pages

Unit-1 Topic 1.4 - Muthithreading - U

nice

Uploaded by

pappu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

ADVANCE JAVA

PROGRAMMING
Unit-1
Prepared By: Ms. Ankita Sharma
Assistant Professor
Department of Computer Science
GTBIT, GGSIPU

Prepared By: Ankita Sharma (Assistant Professor of Computer


1
Science Department)
AGENDA
Multithreading

Prepared By: Ankita Sharma (Assistant Professor of Computer


2
Science Department)
Agenda
• Introduction
• Creating and running a thread
• The thread control methods
• The Thread Life Cycle
• Thread Priorities
• Thread Synchronization
• Inter thread Communication

Prepared By: Ankita Sharma (Assistant Professor of Computer


3
Science Department)
Introduction
• Java provides the facility of multi-threaded programming in which we
write programs that do several things simultaneously.
• A multithreaded program contains two or more parts that can run
concurrently.
• Each part of such a program is called a thread. Each thread defines a
separate path of execution.
• Multi threading is a specialized form of Multi-tasking.

Prepared By: Ankita Sharma (Assistant Professor of Computer


4
Science Department)
Introduction
• In summary, while both multithreading and multitasking involve the
concurrent execution of tasks.
• They differ in terms of the unit of execution, resource sharing,
coordination, communication, overhead, isolation, and parallelism.
• Multithreading is more lightweight and efficient for concurrent
execution within a single process.
• While multitasking allows for the simultaneous execution of multiple
independent processes.

Prepared By: Ankita Sharma (Assistant Professor of Computer


5
Science Department)
Feature Multithreading Multitasking
Definition Execution of multiple threads within a single Concurrent execution of multiple
process. processes.
Unit of Execution Threads within a process. Independent processes.
Processes are isolated from each
Threads share memory space and resources within
Resource Sharing other and have separate memory
a process.
spaces.
Communication between processes
Coordination and communication between threads typically involves inter-process
Coordination
is often simpler, as they share memory. communication mechanisms (e.g.,
pipes, sockets).
May have more overhead due to
Typically less overhead compared to multitasking,
separate memory spaces and
Overhead as threads within the same process share
resource allocation for each
resources.
process.

Prepared By: Ankita Sharma (Assistant Professor of Computer


6
Science Department)
Feature Multithreading Multitasking
Processes use inter-process
Threads communicate directly within the process using
Communication communication mechanisms (e.g.,
shared memory.
pipes, sockets) for communication.
Processes are more isolated from
Threads within a process are less isolated, as they share
Isolation each other, having separate memory
memory and resources.
spaces and resources.
Threads within the same process are dependent on each Processes are independent entities
Dependencies
other and share the same process state. with their own process state.
Multitasking allows for parallel
Multithreading enables parallel execution within a single
Parallelism execution of multiple processes,
process, often leveraging multiple CPU cores.
typically on multi-core processors.
Running multiple applications
An application with multiple threads handling different simultaneously on a computer's
Example tasks concurrently, such as a web server processing operating system, such as a web
multiple client requests. browser, word processor, and media
player.

Prepared By: Ankita Sharma (Assistant Professor of Computer


7
Science Department)
Threads Vs Process
• A thread is the smallest unit of execution within a process. It represents a single
sequence of instructions that can be scheduled for execution by the operating
system's scheduler.
• Multithreading allows for concurrent execution of multiple tasks within a single
process, leading to improved performance and responsiveness.
• Threads can be used to implement parallelism, where multiple threads perform
independent tasks simultaneously, taking advantage of multi-core processors.
• A process is an instance of a program that is being executed by the operating
system. It represents a complete execution environment with its own memory
space, resources, and state.
• Processes provide a high level of isolation and security, as they cannot directly
access each other's memory or resources.
• Processes are well-suited for running independent tasks or programs that need to
be completely isolated from each other.
Prepared By: Ankita Sharma (Assistant Professor of Computer
8
Science Department)
Feature Thread Process
An instance of a program being
Definition Smallest unit of execution within a process.
executed by the operating system.
Processes are isolated from each
Resource Threads within the same process share memory space
other and have separate memory
Sharing and resources.
spaces.
Creation Lightweight to create and manage. Heavier to create and manage.
More overhead due to separate
Overhead Less overhead compared to processes. memory space and resource
allocation.
Processes use inter-process
Threads can communicate directly and share data more
Communication communication mechanisms (e.g.,
efficiently.
pipes, sockets) for communication.

Prepared By: Ankita Sharma (Assistant Professor of Computer


9
Science Department)
Feature Thread Process
More isolated, as processes have
Less isolated, as threads share memory space and
Isolation separate memory spaces and
resources within a process.
resources.
Processes are more secure as they are
Threads within the same process have the same level of
Security isolated from each other and cannot
access privileges.
directly access each other's memory.
Threads within the same process are dependent on each Processes are independent entities
Independence
other and share the same process state. with their own process state.
Multiple processes can execute in
Multithreading enables parallel execution within a
Parallelism parallel, taking advantage of multi-
single process.
core processors.
Processes are suitable for running
Multithreading is suitable for scalable applications
Scalability independent tasks or programs that
requiring concurrent execution of tasks.
need to be completely isolated.

Prepared By: Ankita Sharma (Assistant Professor of Computer


10
Science Department)
Need of Multi-Threading
In absence of multithreading in Java, programs are executed sequentially,
meaning that only one task is executed at a time.
This can lead to several limitations and drawbacks:
1.Limited Concurrency: Without multithreading, Java programs can only
execute one task at a time, which limits the ability to handle concurrent
operations efficiently. For example, in a server application, without
multithreading, the server would only be able to handle one client request at
a time, leading to poor performance and scalability.
2.Reduced Responsiveness: Long-running tasks can block the execution of
subsequent tasks, leading to unresponsive user interfaces and poor user
experience. For instance, if a Java application needs to perform a time-
consuming operation, such as loading data from disk, the entire application
may freeze until the operation is complete.
Prepared By: Ankita Sharma (Assistant Professor of Computer
11
Science Department)
Need of Multi-Threading
3. Underutilization of Hardware Resources: Modern computers often have
multiple CPU cores, but without multithreading, Java programs cannot fully
utilize these resources. This can result in inefficient use of hardware and
decreased performance, especially for computationally intensive tasks that
could benefit from parallel execution.
4. Difficulty in Asynchronous Programming: Asynchronous programming,
which allows tasks to run independently and communicate with each other
asynchronously, becomes challenging without multithreading. Asynchronous
programming is commonly used in event-driven applications, such as GUI
applications and network programming, to handle non-blocking I/O
operations and improve responsiveness.
5. Complexity in Resource Sharing: Without multithreading, sharing
resources such as memory, files, and network connections among different
parts of a Java program becomes more complex and error-prone. Developers
may need to implement custom synchronization mechanisms to ensure thread
safety and prevent data corruption in concurrent access scenarios.
Prepared By: Ankita Sharma (Assistant Professor of Computer
12
Science Department)
Multi-Threading
• Multithreading is a programming concept that allows multiple threads
of execution to run concurrently within a single process.
• A thread can be thought of as an independent sequence of instructions
that can be scheduled for execution by the operating system.
• Multithreading enables parallelism, allowing different parts of a
program to execute simultaneously, thereby improving performance
and responsiveness.
• In a multithreaded application, the main program can create multiple
threads, each performing a specific task concurrently. These threads
can run independently or share resources and communicate with each
other as needed.

Prepared By: Ankita Sharma (Assistant Professor of Computer


13
Science Department)
Multi-Threading
• Overall, multithreading is a powerful technique for building
responsive, efficient, and scalable software applications that can take
advantage of modern hardware architectures with multiple CPU cores.
However, multithreaded programming can also introduce challenges
such as thread synchronization, deadlock, and race conditions, which
must be carefully managed by developers.

Prepared By: Ankita Sharma (Assistant Professor of Computer


14
Science Department)
Key Aspects of Multithreading
1.Concurrency: Multithreading enables concurrent execution of multiple
tasks within a program. This concurrency can lead to better resource
utilization and improved overall performance.
2.Responsiveness: By using multithreading, programs can remain responsive
to user input even while performing time-consuming tasks in the
background. For example, a graphical user interface (GUI) application can
update its interface and handle user interactions while simultaneously
performing calculations or fetching data from the network in separate
threads.
3.Parallelism: Multithreading allows for true parallelism, where multiple
threads execute simultaneously on multi-core processors. This can lead to
significant performance gains for CPU-bound tasks that can be divided into
smaller subtasks that can run in parallel.
Prepared By: Ankita Sharma (Assistant Professor of Computer
15
Science Department)
Key Aspects of Multithreading
4. Responsiveness: Multithreading helps improve the responsiveness of
applications by allowing time-consuming tasks to be executed in the
background while the main thread remains responsive to user input. For
example, in graphical user interfaces (GUIs), multithreading can prevent
the UI from freezing while performing tasks such as loading data from
disk or processing large amounts of data.
5. Resource Sharing: Multithreading facilitates sharing of resources such
as memory, files, and network connections among multiple threads
within the same process. This enables efficient communication and data
exchange between threads and simplifies coordination between different
parts of a program.

Prepared By: Ankita Sharma (Assistant Professor of Computer


16
Science Department)
Key Aspects of Multithreading
6. Modularity and Maintainability: Multithreading allows developers to
design applications in a modular and scalable manner by dividing
complex tasks into smaller, independently executing threads. This can
improve code organization, readability, and maintainability, as well as
facilitate code reuse and parallel development.
7. Synchronization: In multithreaded programming, synchronization
mechanisms such as locks, mutexes, and semaphores are used to
coordinate access to shared resources and ensure data consistency. These
mechanisms help prevent race conditions and ensure that threads operate
correctly in a concurrent environment.

Prepared By: Ankita Sharma (Assistant Professor of Computer


17
Science Department)
Methods of Multithreading in Java

start() The start method initiates the execution of a thread

The currentThread method returns the reference to the currently executing


currentThread()
thread object.

run() The run method triggers an action for the thread

isAlive() The isAlive method is invoked to verify if the thread is alive or dead

sleep() The sleep method is used to suspend the thread temporarily

The yield method is used to send the currently executing threads to standby
yield()
mode and runs different sets of threads on higher priority

Prepared By: Ankita Sharma (Assistant Professor of Computer


18
Science Department)
Methods of Multithreading in Java

The yield method is used to send the currently executing threads to standby
yield()
mode and runs different sets of threads on higher priority

suspend() The suspend method is used to instantly suspend the thread execution

resume() The resume method is used to resume the execution of a suspended thread only

The interrupt method triggers an interruption to the currently executing thread


interrupt()
class

destroy() The destroy method is invoked to destroy the execution of a group of threads

stop() The stop method is used to stop the execution of a thread

Prepared By: Ankita Sharma (Assistant Professor of Computer


19
Science Department)
Thread Life Cycle
.

Prepared By: Ankita Sharma (Assistant Professor of Computer


20
Science Department)
Thread Life Cycle
.

Prepared By: Ankita Sharma (Assistant Professor of Computer


21
Science Department)
Threads can go to the non-runnable state by
choice.
Let’s have a look at the methods available to us to give-up CPU time by choice:
• sleep(long millis) — This method causes the calling thread to sleep for the duration
provided as the parameter. After the sleep duration, the thread moves back to the
runnable state waiting for the scheduler to pick it up for execution.
• yield()— This method is like a notification to the scheduler, that the thread is ready to
give up execution. The scheduler then decides, based on other live threads and their
priorities, if it wants to move the calling thread to runnable and give the CPU time to
other threads, or keep running the existing thread.
• join() — join is called to pause the execution of the program until the thread calling the
join method is terminated.

Prepared By: Ankita Sharma (Assistant Professor of Computer


22
Science Department)
Thread Life Cycle
1. New: When a thread is created, it is in the “New” state. In this
state, the thread has been instantiated but has not yet started its
execution. You can create a new thread by instantiating a Thread
object or by creating a class that extends the Thread class and
then creating an instance of that class.
2. Runnable: A thread enters the “Runnable” state when it is ready
to execute but hasn’t been scheduled for execution by the
operating system yet. This means that the start() method has been
called on the thread, or the thread has been added to a thread
pool. However, it doesn't necessarily mean that the thread is
actively executing; it might be waiting for its turn to run.

Prepared By: Ankita Sharma (Assistant Professor of Computer


23
Science Department)
Thread Life Cycle
3. Running: In the “Running” state, the thread’s code is actively
executing. When the operating system schedules the thread, it starts
executing its run() method or the code provided to it. A thread can be
in this state for a variable amount of time.
4. Blocked/Waiting: A thread may enter the “Blocked” or “Waiting”
state when it is temporarily inactive or waiting for a specific
condition to be met. This can happen for various reasons, such as
when a thread is waiting for I/O operations, synchronization locks, or
for another thread to notify it. Threads in this state are not executing
their code.

Prepared By: Ankita Sharma (Assistant Professor of Computer


24
Science Department)
Thread Life Cycle
5. Timed Waiting: Threads in this state are similar to the “Waiting”
state but with a time limit. They are waiting for a specific condition
but with a timeout. For example, a thread might be waiting for a
resource to become available for a certain amount of time before
giving up and moving to another state.
6. Terminated/Dead: A thread enters the “Terminated” or “Dead”
state when it has completed its execution or when it is explicitly
stopped. Once a thread is terminated, it cannot be restarted. You can
check if a thread is in the terminated state using the Thread.isAlive()
method.

Prepared By: Ankita Sharma (Assistant Professor of Computer


25
Science Department)
Thread Life Cycle
1. New ( ): A thread is created by instantiating the Thread class. At this point, it
is in the new state.
Thread myThread = new Thread();
2. Runnable (): After the thread is created, it moves to the runnable state when
the start() method is called. The start() method internally calls the run() method,
and the thread becomes ready for execution.
myThread.start(); // Moves the thread to the runnable state
3. Running: Once the scheduler selects the thread for execution, it enters the
running state. The run() method contains the code that will be executed when the
thread is running.
public void run() {
// Code to be executed when the thread is running
}

Prepared By: Ankita Sharma (Assistant Professor of Computer


26
Science Department)
Thread Life Cycle
4. Blocked (or Waiting): A running thread may enter the blocked
state if it encounters an operation that makes it wait, such as calling
sleep(), wait(), or performing I/O operations.
// Example: Thread sleeps for 1 second
try {
Thread.sleep(1000); // Thread enters blocked state for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}

Prepared By: Ankita Sharma (Assistant Professor of Computer


27
Science Department)
Thread Life Cycle
5. Terminated (or Dead): The thread enters the terminated state
when the run() method completes its execution or when an uncaught
exception occurs.
// Example: Completing the run method
public void run() {
// Code to be executed when the thread is running
// ...
// The thread terminates when this method completes
}

Prepared By: Ankita Sharma (Assistant Professor of Computer


28
Science Department)
Note
• It’s important to note that the start() method should be used to initiate
the execution of a thread.
• The actual code to be executed should be placed in the run() method.
• Calling run() directly won’t create a new thread; it will execute the
run() method in the context of the current thread.
• Using start() is essential for multithreading, as it signals the system to
create a new thread and invoke the run() method in that new thread.

Prepared By: Ankita Sharma (Assistant Professor of Computer


29
Science Department)
Two Main ways to create threads in Java:
1. Extending the Thread class: We can extend the Thread class and
override the run() method to define the thread’s behavior.
To extend the Thread class, we must override the run() method. The
run() method contains the code that the thread will execute.
Once we have created a thread, we can start it by calling the start()
method. The start() method causes the thread to begin executing the
run() method.
2. Implementing the Runnable interface: We can implement the
Runnable interface and pass an instance of the class to the Thread
constructor.

Prepared By: Ankita Sharma (Assistant Professor of Computer


30
Science Department)
1. Thread Class
In Java, you can create and manage threads using the Thread class. You
can create a new thread by extending the Thread class and overriding its
run() method, which contains the code that will be executed in the new
thread.

Prepared By: Ankita Sharma (Assistant Professor of Computer


31
Science Department)
// Creating thread By Extending To Thread class

Prepared By: Ankita Sharma (Assistant Professor of Computer


32
Science Department)
// Creating thread By Extending To Thread class

Prepared By: Ankita Sharma (Assistant Professor of Computer


33
Science Department)
2. Runnable Interface
An alternative way to create threads in Java is by implementing the
Runnable interface. This interface defines a single run() method, and
you can pass a Runnable object to a Thread constructor.

Prepared By: Ankita Sharma (Assistant Professor of Computer


34
Science Department)
2. Runnable Interface
An alternative way to create threads in Java is by implementing the
Runnable interface. This interface defines a single run() method, and
you can pass a Runnable object to a Thread constructor.
1. Create a class that implements Runnable.
2. Provide a run method in the Runnable class.
3. Create an instance of the Thread class and pass our Runnable object
to its constructor as a parameter.
4. Call the Thread object’s start method.

Prepared By: Ankita Sharma (Assistant Professor of Computer


35
Science Department)
// Creating thread using Runnable interface

Prepared By: Ankita Sharma (Assistant Professor of Computer


36
Science Department)
// Creating thread using Runnable interface

Prepared By: Ankita Sharma (Assistant Professor of Computer


37
Science Department)
Thread Priorities
❑Thread priority represents a number between 1 to 10. It helps the operating
system to determine the order in which threads are scheduled.
❑Priority of a Thread (Thread Priority)
• Each thread has a priority. Priorities are represented by a number between 1
and 10.
• In most cases, the thread scheduler 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. Note that not only JVM a Java programmer can also
assign the priorities of a thread explicitly in a Java program.
Prepared By: Ankita Sharma (Assistant Professor of Computer
38
Science Department)
Thread Priorities
3 constants defined in Thread class:
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
Note: Default priority of a thread is 5 (NORM_PRIORITY). The value
of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Prepared By: Ankita Sharma (Assistant Professor of Computer


39
Science Department)
Thread Priorities
Setter & Getter Method of Thread Priority. Let's discuss the setter
and getter method of the thread priority.
1. public final int getPriority(): The java.lang.Thread.getPriority()
method returns the priority of the given thread.
2.public final void setPriority(int newPriority): The
java.lang.Thread.setPriority() method updates or assign the priority of
the thread to newPriority.
The method throws IllegalArgumentException if the value newPriority
goes out of the range, which is 1 (minimum) to 10 (maximum).

Prepared By: Ankita Sharma (Assistant Professor of Computer


40
Science Department)
Static fields for thread priority defined in
Thread class:
1. public static final int MIN_PRIORITY
The minimum priority that a thread can have.
Default value : 1
2. public static final int NORM_PRIORITY
The default priority that is assigned to a thread.
Default value : 5
3. public static final int MAX_PRIORITY
The maximum priority that a thread can have.
Default value : 10
Prepared By: Ankita Sharma (Assistant Professor of Computer
41
Science Department)
class Test extends Thread{
public void run(){
System.out.println("Priority of running thread: " +
Thread.currentThread().getPriority());
}
}

public class ThreadPriorityExample {


public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();
Test thrd3 = new Test();

//set thread priority.


thrd1.setPriority(Thread.MIN_PRIORITY);
thrd2.setPriority(Thread.NORM_PRIORITY);
thrd3.setPriority(Thread.MAX_PRIORITY);

//start the thread.


thrd1.start();
thrd2.start();
thrd3.start();
}
}
Prepared By: Ankita Sharma (Assistant Professor of Computer
42
Science Department)
class Test extends Thread{
public void run(){
System.out.println("Priority of running thread: " +
Thread.currentThread().getPriority());
}
}

public class ThreadPriorityExample {


public static void main(String args[]){
//creating thread.
Test thrd1 = new Test();
Test thrd2 = new Test();
Test thrd3 = new Test();

//set thread priority.


thrd1.setPriority(Thread.MIN_PRIORITY);
thrd2.setPriority(Thread.NORM_PRIORITY);
thrd3.setPriority(Thread.MAX_PRIORITY);

//start the thread.


thrd1.start();
thrd2.start();
thrd3.start();
}
}
Prepared By: Ankita Sharma (Assistant Professor of Computer
43
Science Department)
Thread Synchronization
• Thread synchronization is the coordination of multiple threads to ensure
they access shared resources or critical sections of code in a mutually
exclusive manner.
• In multi-threaded environments, where multiple threads are executing
concurrently, synchronization is essential to prevent race conditions, data
corruption, and ensure the consistency and integrity of shared data.
• Thread synchronization in java is a way of programming several threads to
carry out independent tasks easily. It is capable of controlling access to
multiple threads to a particular shared resource.
The main reason for using thread synchronization are as follows:
• To prevent interference between threads.
• To prevent the problem of consistency.
Prepared By: Ankita Sharma (Assistant Professor of Computer
44
Science Department)
Two Types of Thread Synchronization
1. Process synchronization- The process means a program in execution and runs
independently isolated from other processes. CPU time, memory, etc resources are
allocated by the operating system.
2. Thread synchronization- It refers to the concept where only one thread is
executed at a time while other threads are in the waiting state. This process is
called thread synchronization. It is used because it avoids interference of thread
and the problem of inconsistency.
In java, thread synchronization is further divided into two types:
• Mutual exclusive- it will keep the threads from interfering with each other while
sharing any resources.
• Inter-thread communication- It is a mechanism in java in which a thread
running in the critical section is paused and another thread is allowed to enter or
lock the same critical section that is executed.
Prepared By: Ankita Sharma (Assistant Professor of Computer
45
Science Department)
Mutual Exclusive
It is used for preventing threads from interfering with each other and to
keep distance between the threads.
Mutual exclusive is achieved using the following:
• Synchronized Method
• Synchronized Block
• Static Synchronization

Prepared By: Ankita Sharma (Assistant Professor of Computer


46
Science Department)
Mutual Exclusive is achieved Using

1. Synchronized Method
It is a method that can be declared synchronized using the keyword
“synchronized” before the method name.
By writing this, it will make the code in a method thread-safe so that no
resources are shared when the method is executed.
Syntax: synchronized public void methodName() { }

Prepared By: Ankita Sharma (Assistant Professor of Computer


47
Science Department)
Mutual Exclusive is achieved Using

2. Synchronized Block
If a block is declared as synchronized then the code which is written
inside a method is only executed instead of the whole code.
It is used when sequential access to code is required.
Syntax: synchronized (object reference)
{
// Insert code here
}

Prepared By: Ankita Sharma (Assistant Professor of Computer


48
Science Department)
Mutual Exclusive is achieved Using

3. Static Synchronization
The method is declared static in this case.
It means that lock is applied to the class instead of an object and only
one thread will access that class at a time.
Syntax: synchronized static return type class name{}

Prepared By: Ankita Sharma (Assistant Professor of Computer


49
Science Department)
Inter thread Communication
• Inter-thread communication is also known as Cooperation in Java.
• Inter-thread communication in Java 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.
• Polling: The process of testing a condition repeatedly till it becomes
true is known as polling. Polling is usually implemented with the help
of loops to check whether a particular condition is true or not. If it is
true, a certain action is taken. This wastes many CPU cycles and
makes the implementation inefficient.

Prepared By: Ankita Sharma (Assistant Professor of Computer


50
Science Department)
Inter thread Communication
• To avoid polling, Java uses three methods, namely, wait(), notify(), and
notifyAll(). All these methods belong to object class as final so that all
classes have them. They must be used within a synchronized block only.
• Synchronized Blocks/Methods: Synchronization is necessary to ensure
that only one thread can execute a critical section of code at any given time.
This prevents race conditions and ensures thread safety.
❑ wait(): It tells the calling thread to give up the lock and go to sleep until
some other thread enters the same monitor and calls notify().
❑ notify(): It wakes up one single thread called wait() on the same object. It
should be noted that calling notify() does not give up a lock on a resource.
❑ notifyAll(): It wakes up all the threads called wait() on the same object.

Prepared By: Ankita Sharma (Assistant Professor of Computer


51
Science Department)
1) wait() method
• The 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.
1. public final void wait()throws InterruptedException
It waits until object is notified.
2. public final void wait(long timeout)throws InterruptedException
It waits for the specified amount of time.

Prepared By: Ankita Sharma (Assistant Professor of Computer


52
Science Department)
2) notify() method
• The 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.
• They are part of the Object class and are used for inter-thread
communication in the context of synchronization.
• In other words this method is used to wake up a single thread that is waiting
on the object's monitor. If multiple threads are waiting on the monitor, the
JVM's choice of which thread to wake is not specified and may vary. The
awakened thread will then compete with other threads for the lock on the
object.
Syntax: public final void notify()
Prepared By: Ankita Sharma (Assistant Professor of Computer
53
Science Department)
3) notifyAll() method
• It part of the Object class and are used for inter-thread communication
in the context of synchronization.
• This method is used to wake up all the threads that are waiting on the
object's monitor. All threads are notified and they will then compete
for the lock to acquire it.
• Wakes up all threads that are waiting on this object's monitor.
• Syntax: public final void notifyAll()

Prepared By: Ankita Sharma (Assistant Professor of Computer


54
Science Department)
Understanding Inter thread
Communication
.

Prepared By: Ankita Sharma (Assistant Professor of Computer


55
Science Department)
Understanding Inter thread Communication
1.Threads enter to acquire lock.
2.Lock is acquired by on thread.
3.Now thread goes to waiting state if you
call wait() method on the object.
Otherwise it releases the lock and exits.
4.If you call notify() or notifyAll() method,
thread moves to the notified state
(runnable state).
5.Now thread is available to acquire lock.
6.After completion of the task, thread
releases the lock and exits the monitor
state of the object.
Prepared By: Ankita Sharma (Assistant Professor of Computer
56
Science Department)
Differences

Wait Sleep
• The wait() method releases the • The sleep() method doesn't release
lock. the lock.
• It is a method of Object class • It is a method of Thread class
• It is the non-static method • It is the static method
• It should be notified by notify() or • After the specified amount of time,
notifyAll() methods sleep is completed.

Prepared By: Ankita Sharma (Assistant Professor of Computer


57
Science Department)
THANK YOU

Prepared By: Ankita Sharma (Assistant Professor of Computer


58
Science Department)

You might also like