Close

Simple Wait / Notify Thread Example

This is a simple Wait / Notify example. I am utilizing an Object for synchronization purpose. You can synchronize on This or any other object. However, a dedicated object that you use only for synchronization will give you a better understanding of code and eases debugging.

package com.sheidaei.sampleThread;

/**
 * Created with IntelliJ IDEA.
 * User: shahin
 * Date: 6/7/13
 * Time: 12:34 PM
 * To change this template use File | Settings | File Templates.
 */
public class SimpleWaitNotifyThread implements Runnable{

    private String action;
    private final static Object lockObject = new Object();

    public SimpleWaitNotifyThread(String action) {
        this.action = action;
        System.out.println(“>>> Constructor. Actions is set to ” + getAction());
    }

    @Override
    public void run() {
        System.out.println(” >> “+getAction()  + ” section started.”);

        synchronized (lockObject){
            if(getAction().equalsIgnoreCase(“wait”))
            {
                try {
                    System.out.println(”  > Before wait”);
                    lockObject.wait();
                    System.out.println(”  > After wait”);
                } catch (InterruptedException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
            else
            {
                try {
                    //Pretend we are doing something
                    System.out.println(”  > Before sleep”);
                    Thread.sleep(100);
                    System.out.println(”  > After sleep”);
                } catch (InterruptedException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                //Then we notify
                System.out.println(”  > Before notify”);
                lockObject.notify();
                System.out.println(”  > After notify”);

            }
        }

        System.out.println(” >> “+getAction() + ” section stopped.”);
    }

    public static void main(String args[])
    {
        System.out.println(“Main Thread started.”);

        SimpleWaitNotifyThread thread1 = new SimpleWaitNotifyThread(“wait”);
        SimpleWaitNotifyThread thread2 = new SimpleWaitNotifyThread(“notify”);

        new Thread(thread1).start();
        new Thread(thread2).start();

        System.out.println(“Main Thread finished.”);
    }

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *