This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.