Simple wait and notify example in Java

This example demonstrate wait and notify example. Main thread(ThreadA) will create threadB and will start threadB. After threadB started, it just print that it is started and will go to WAITING state by calling wait(). Meanwhile threadA goes to sleep for 3 seconds and will print that it is awaked and will notify threadB by calling notify(). This will cause to threadB goes to RUNNABLE state. Then it will resume the threadB's execution and will print that it is notified.

public class ThreadA {
    public static void main(String[] args) throws InterruptedException {
        ThreadB threadB = new ThreadB();
        Thread thread = new Thread(threadB);
        thread.start();
        Thread.sleep(3000);
        System.out.println("threadA is awaked.......");
        synchronized (threadB) {
            threadB.notify();
        }

    }
}

public class ThreadB implements Runnable {
    public void run() {
        System.out.println("threadB is started................");
        synchronized (this) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("threadB is notified.............");
        }
    }
}

Note that when we call wait() and notify(), it should call inside synchronised context. Otherwise it will throw java.lang.IllegalMonitorStateException. We have to pass a lock object to the synchronised block. That object will be blocked during the execution of synchronisation block. In this case I pass the threadB itself as the lock object.

Comments

Popular posts from this blog

Application Whitelist and Blacklist Feature in WSO2 EMM

WSO2 APP Manager(APPM) and WSO2 Enterprise Mobility Manager (EMM) integration

How to map existing OAuth applications in WSO2 API Manager User Interface