In this segment of tutorial we will learn about the wait and notify methods in Thread.Then We will create an example and use these methods.
In this segment of tutorial we will learn about the wait and notify methods in Thread.Then We will create an example and use these methods.
public class bus { public static void main(String[] args) throws InterruptedException { passenger p = new passenger(); p.start(); synchronized (p) { System.out.println("passenger is waiting for the bus "); p.wait(); System.out.println("passenger got notification"); } System.out.println("after "+p.total+" time"); } } class passenger extends Thread { int total = 0; public void run() { synchronized (this) { System.out.println("wait .... "); for (int i = 0; i <= 1000; i++) total = total + i; System.out.println("passenger is given notification call"); notify(); } } }
Output :
passenger is waiting for the bus wait .... passenger is given notification call passenger got notification after 500500 time