Tutorials Hut

Tutorials Hut

sleep, wait, notify and notifyAll, synchronized Methods of Thread In Java 

sleep, wait, notify and notifyAll are most useful methods related to thread. We look into details of sleep, wait, notify and notifyAll, synchronized Methods of Thread In Java in this article.

sleep() Method in Thread

 sleep() method belongs to Thread class and when it is called it will make the current running thread sleep for specified time duration.

Example:

Thread.sleep(1000)

This will make the current running thread sleep for 1000 ms ( or 1 second).

wait() Method In Multithreading

The wait method belongs to the object of the class(please note sleep method belongs to Thread class), so any object can have a wait method.

Whenever wait is invoked on an object it will pause the execution of the current thread on it until notified by another thread using notify() or notifyAll() method.

Difference between sleep() and wait() methods

1. sleep() method belongs to the Thread class while wait() belongs to the object of class.

2. sleep() method makes current thread sleep for given time while wait() will wait until notified using notify() and notifyAll()

3. sleep() is used with class and wait with objects.

4. sleep() does not release the lock on the current monitor but wait() releases the lock.

notify() and notifyAll() Methods in Multithreading

notify() and notifyAll() both methods belong to the object. Whenever notify() is invoked that means the current thread on the object is done and the other thread which is waiting on the same object may start execution.

notifyAll() will notify all waiting threads on objects to start execution.

Race condition, dead lock and synchronized Methods and Blocks in Thread

Race Condition: When two or more threads try to access the same resource at same time it may cause a race condition between threads to get lock on a common object. This may result in invalid state or value or resource or object.

Deadlock: Sometimes it may happen that one thread has taken a lock on a resource object and is waiting for another thread to proceed and another thread might be waiting for the first thread to release the lock on object to complete the execution and hence none of them is actually executing and this is called dead lock.

synchronized Methods and Blocks:

To avoid race conditions and deadlock, in Java we have synchronized keywords which we can use with definition of method to make it synchronized which means at a time one thread can get lock on object and execute the code in method, no other thread will get access until thread will lock completes execution. Similar to method we may also use synchronized keyword with a block of code instead the entire method to narrow down the locked area.

Example of synchronized methods and blocks:

package threads;
class Account{

int accountBalance=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw");

if(this.accountBalance<amount){
System.out.println("Less balance; waiting for deposit.");
try{wait();}catch(Exception e){}
}
this.accountBalance-= amount;
System.out.println("withdraw completed.");
}

void deposit(int amount){
synchronized(this){
System.out.println("going to deposit.");
this.accountBalance += amount;
System.out.println("deposit completed.");
notify(); //will notify first thread i am done you go ahead.
}
}
}

Example of wait, notify() and synchronized methods

See below deposit() and withdraw() problem solved using wait and notify().

Example

package threads;
class Account{
int accountBalance=10000;

synchronized void withdraw(int amount){
    System.out.println("going to withdraw");
    if(this.accountBalance<amount){
        System.out.println("Less balance; waiting for deposit.");
        try{wait();}catch(Exception e){}
    }
    this.accountBalance-= amount;
    System.out.println("withdraw completed...");
}

synchronized void deposit(int amount){
    System.out.println("going to deposit.");
    this.accountBalance+= amount;
    System.out.println("deposit completed.");
    notify(); //will notify first thread i am done you go ahead
}
}

public class WaitAndNotifyExamples{
public static void main(String args[]){
    final Account c = new Account();
    //Thread using lambda
    new Thread(() -> c.withdraw(15000)).start();
    new Thread(() -> c.deposit(10000)).start();
}}

Output

going to withdraw
Less balance; waiting for deposit.
going to deposit.
deposit completed.
withdraw completed.

NOTE:

Any static method synchronized will ensure that only one thread will have access to that in the entire JVM.

Next Article


















  • Scroll to Top