Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A good small example to demonstrate wait() and notify() method in java

Can anybody please provide me a good small example demonstrate wait() and notify() functionality in java. I've tried with the below piece of code but it's not showing what i expected.

public class WaitDemo {
    int i = 10;

    int display() {
        System.out.println("Lexmark");
        i++;
        return i;
    }
}
public class ClassDemo1 extends Thread {

    private WaitDemo wd = new WaitDemo();

    public static void main(String[] args) {
        ClassDemo1 cd1 = new ClassDemo1();
        ClassDemo1 cd2 = new ClassDemo1();
        cd1.setName("Europe");
        cd2.setName("America");
        cd1.start();
        cd2.start();

    }

    synchronized void display() {
        System.out.println("Hello");
        notifyAll();
    }

    public void run() {

        synchronized (this) {
            try {
                {
                    notify();
                    System.out.println("The thread is " + currentThread().getName());
                    wait();
                    System.out.println("The value is " + wd.display());
                }
            } catch (InterruptedException e) {

            }

        }
    }
}

The issue is that the method in the class WaitDemo is not getting executed and as per my idea the SOP after wait() should execute. Please help me out on this.

like image 702
Sourav Bag Avatar asked Dec 02 '11 15:12

Sourav Bag


People also ask

What is wait () notify () in Java with example?

Simply put, calling wait() forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object. For this, the current thread must own the object's monitor.

What is the purpose of sleep () wait () notify () methods in Java?

It tells the calling thread (a.k.a Current Thread) to wait until another thread invoke's the notify() or notifyAll() method for this object, The thread waits until it reobtains the ownership of the monitor and Resume's Execution. Wait() method belongs to Object class. Sleep() method belongs to Thread class.

How do you use wait and notify in Java?

The wait() method causes the current thread to wait until another thread invokes the notify() or notifyAll() methods for that object. The notify() method wakes up a single thread that is waiting on that object's monitor. The notifyAll() method wakes up all threads that are waiting on that object's monitor.

What is the purpose of wait () and notify () methods?

What are Wait () and Notify() methods? To tackle the multithreading problem, methods like Wait and Notify in Java are used. The Object class uses these three final methods that allow threads to communicate about the locked status of a resource.


2 Answers

You've got two levels of braces { in your try block. If you remove the inner set (which doesn't appear to do anything), does that fix the problem?

There are several examples around, all of which demonstrate the use. The last link is a set of results that can help you out. If you need more specific things, let me know what it is that your app is trying to do, and I can try to find examples that are more specific to your situation.

  • http://www.javamex.com/tutorials/wait_notify_how_to.shtml
  • http://www.java-samples.com/showtutorial.php?tutorialid=306
  • http://www.coderanch.com/t/234235/threads/java/Wait-Example
  • https://www.google.com/search?q=wait%28%29+example+java&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
like image 109
jefflunt Avatar answered Sep 20 '22 15:09

jefflunt


Below is an example of wait & notify in the Object class. The customer is trying to withdraw money of value 2000 but the account is having only 1000 so it has to wait for the deposit. Once the deposit is made, then the customer will be able to withdraw the amount. Until the deposit is made, the customer will be waiting.

class Cust {

    private int totalAmount = 1000;

    public synchronized void withdrawal(int amount) {
        System.out.println("Total amount " + totalAmount + " withdrawing amount " + amount);
        while (this.totalAmount < amount) {
            System.out.println("not enough amount..waiting for deposit..");
            try { wait(); } catch (Exception e) {}
        }
        this.totalAmount -= amount;     
        System.out.println("Withdrawal successful.. Remaining balance is "+totalAmount);    
    }

    public synchronized void deposit(int amount){
        System.out.println("Depositing amount "+amount);
        this.totalAmount += amount;
        System.out.println("deposit completed...and Now totalAmount is " + this.totalAmount);
        notify();
    }
}

class Depo implements Runnable {
    Cust c; int depo;

    Depo(Cust c, int depo){
        this.c = c;
        this.depo = depo;
    }

    @Override
    public void run() {
        c.deposit(depo);    
    }
}

class Withdrawal implements Runnable {
    Cust c; int with;

    Withdrawal(Cust c, int with){
        this.c = c;
        this.with = with; 
    }

    @Override
    public void run() {
        c.withdrawal(with);
    }
}

public class ObjectWaitExample {

    public static void main(String[] args) {
        Cust c = new Cust();
        Thread w = new Thread(new Withdrawal(c, 2000));
        Thread d1 = new Thread(new Depo(c, 50));
        Thread d2 = new Thread(new Depo(c, 150));
        Thread d3 = new Thread(new Depo(c, 900));
        w.start();
        d1.start();
        d2.start();
        d3.start();
    }

}
like image 41
Vijay Bhatt Avatar answered Sep 19 '22 15:09

Vijay Bhatt