Learn about wait, sleep and yield in java:
Java wait and notify Example:
public class WaitForNotification{
public static void main(String []args) throws InterruptedException{
Passenger psg = new Passenger();
psg.start();
// In synchronized block call wait method on newly created Passenger object
Synchronized(psg){
System.out.println(" Passenger is waiting for the notification.");
psg.wait();
System.out.println(" Passenger got notified.");
}
}
}
class Passenger extends Thread{
public void run(){
Syncronized(this){
System.out.println(" Wait...........");
// Here add code befor bus gets notified
System.out.println("Passenger is given notification call");
notify()
}
}
}
Java wait and notify Example:
- Wait and notify both are the methods of Object class.
- Wait makes the object to wait for the given time or till it's notified.
- Once wait is invoked, object lock is being released and other thread can work on object.
- Both methods are called in the synchronized context.
public class WaitForNotification{
public static void main(String []args) throws InterruptedException{
Passenger psg = new Passenger();
psg.start();
// In synchronized block call wait method on newly created Passenger object
Synchronized(psg){
System.out.println(" Passenger is waiting for the notification.");
psg.wait();
System.out.println(" Passenger got notified.");
}
}
}
class Passenger extends Thread{
public void run(){
Syncronized(this){
System.out.println(" Wait...........");
// Here add code befor bus gets notified
System.out.println("Passenger is given notification call");
notify()
}
}
}