• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Interaction between Threads

October 18, 2011 By j2eereference Leave a Comment

Threads communicate with one another to know their locking status, status of an event etc. Thread interacts with one another using Object class’s methods and they are:

  • public final void wait()  throws InterruptedException
  • public final void notify()
  • public final void notifyAll().

Note: wait(), notify() and notifyAll() must be called within a synchronized block, a thread cannot call wait() or notify() method on an object unless it acquires a lock on an object.

wait() Method

A thread is made to be waiting in a pool or waiting room until it gets notification from another thread. A thread calls wait() method to go and wait for some time. From this moment it will not execute any instruction until it gets notification. If many threads are waiting on the same object, only one thread will be allowed to proceed with its execution and it’s not guaranteed that the thread waiting for long will get a lock on that object. A thread can be interrupted when it was waiting, so use try/catch block around the wait() method to take care of exception.

1
2
3
4
5
try {
wait();
} catch(InterruptedException ex) {
//catch exception
}

 

The 2nd form of wait() method which takes number of millisecond as a parameter as a maximum time to wait. It will continue its execution whenever it gets notification or specified time has elapsed.

1
2
3
4
5
6
7
try{
synchronized(b){
b.wait(2000); //waits maximum specified  time for only 2 sec
}
}catch(InterruptedException ex) {
//catch exception
}

Note : If thread calls wait() and it does not owns the lock, it will throw an runtime IllegalMonitorStateException.

notify() and notifyAll() Methods

The notify() method sends a notification  to a single thread which is waiting on the object’s lock.  The notify()  method wakes up only one thread which is waiting on object’s lock. If it is only single thread it will get object’s lock; if there are many threads which are waiting for object’s lock  then it’s uncertain that which thread will get notification by notify()  method.

The notifyAll() method notifies to all the threads which are waiting on a particular object’s lock.  If there  are not threads waiting for an object’s lock, notify() and notifyAll() has no effects.

When the wait() method is called on an object, the thread executing the code releases its lock on the object immediately. When notify() is called, thread does not releases its lock until it completes the synchronized block.

A simple example to calculate sum, using wait() and notify() method in synchronized block

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<strong>public</strong> <strong>class</strong> Addition <strong>extends</strong> Thread {
<strong>int</strong> sum=0;
<strong>public</strong> <strong>void</strong> run()
{
<strong>synchronized</strong> (<strong>this</strong>)//thread got lock
{
System.<em>out</em>.println("in synchronized block and calculating");
<strong>for</strong>(<strong>int</strong>i=0;i&lt;=400;i++)
{
sum=sum+i;
}
notify();    //thread releases lock
}
}

} 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<strong>public</strong> <strong>class</strong> Test {
<strong>public</strong> <strong>static</strong> <strong>void</strong> main(String [] args)<strong>throws</strong> InterruptedException
{
Addition b =<strong>new</strong> Addition();
b.start();
<strong>synchronized</strong>(b)     //thread got lock
{
System.<em>out</em>.println("calling wait method");
b.wait();
System.<em>out</em>.println("Notification received");
}
System.<em>out</em>.println(b.sum);
}
}

output:

calling wait method

in synchronized block and calculating

Notification received

80200

Related Posts

  • UncaughtExceptionHandler in java
  • How to generate and resolve OutOfMemoryError?
  • Difference between Spring’s Singleton scope & Singleton Design pattern
  • How to stop a thread?
  • Interrupting a thread in java
  • What is ThreadLocal in Java ?
  • ArrayList custom Implementation
  • Difference between volatile and synchronized keyword?
  • How to write thread safe code?
  • How to avoid deadlock in java ?

Filed Under: Core Java

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.