Saturday, May 5, 2012

A perfect example to understand wait and notify in threads

class myWriterThread implements Runnable
{
    private mClass userInput;
    public myWriterThread(mClass userInput) {
        this.userInput = userInput;
    }
    public void run() {
        userInput.waitForInput();
    }
}
class myReaderThread implements Runnable
{
    private mClass userInput;

    public myReaderThread(mClass userInput) {
        this.userInput = userInput;
    }


    public void run() {
        userInput.ReadInput();
    }
}
class mClass 
{
    public synchronized void waitForInput() 
    {
        while(!userInput.equals("Y"))
        {
            try
            {
                System.out.println("Going to wait");
                wait();
            }
            catch(InterruptedException e)
            {
                System.out.println(e.getMessage());
                System.out.println("Got interrupted");
            }
        }
        System.out.println("Wait for Input notified");
    }
    public synchronized void ReadInput()
    {
       try
        {
             userInput="Y";
             System.out.println("Reader has set userInput to Y");
             notify();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
        System.out.println("I am exiting ReadInput");
    }        
    private String userInput;

    public mClass(String userInput) {
        this.userInput = userInput;
    }
}
public class CustomClass
{
    public static void main(String args[])
    {
        mClass m = new mClass("N");
        Thread t1 = new Thread(new myWriterThread(m));
        Thread t3 = new Thread(new myWriterThread(m));
        t3.start();
        t1.start();
        Thread t2 = new Thread(new myReaderThread(m));
        t2.start();
    }
}

No comments:

Post a Comment