JAVA Method Wait

The Wait method in Java hold the thread to release the lock till the thread hold the object.

JAVA Method Wait

The Wait method in Java hold the thread to release the lock till the thread hold the object.

JAVA Method Wait

JAVA Method Wait

     

The Wait method in Java hold the thread to release the lock till the thread hold the object. The most important point is to be remember that wait method is used inside the synchronized code. The wait ( ) is defined inside the object class. When the wait method is called the following event to be occurred -

  1. The other thread invoke the notify method for the this object.
  2. The other thread invoke the notify all ( ) method for the same object.
  3. The thread try to interrupt.

Understand with Example

The Tutorial understand a code that helps you to understand  Java method Wait.In this Tutorial we have a class Wait Method declare a initialized string variable st .Inside the main method we instantiate a wait method class. 

wait.start ( ) : This causes the thread to start  or begin execution. The start ( ) method also allocate the system resources required for a thread. The current thread  schedule to run  and invoke the run method ( ).The print ln print the value "Hello".

notify All ( ) :This is used to wake up all the thread waiting for allocating the resources.

wait.valchange ( ) :The wait object call a Val change ( ) method, Finally the println print the value to be changed from Hello to Hello world.

Here is the code:

public class WaitMethod extends Thread{
String st="Hello";
public static void main(String args[]) {
WaitMethod wait=new WaitMethod();
wait.start();
new Example(wait);
}
public void run(){
try {
synchronized(this){
wait();
System.out.println("value is :"+st)
}
}catch(Exception e){}
}
public void valchange(String st){ 
this.st=st; 
try {
synchronized(this) {
notifyAll()
}
}catch(Exception e){}
}
}
class Example extends Thread{
WaitMethod wait;
Example(WaitMethod wait) {
this.wait=wait;
start();
}
public void run(){
try{
System.out.println("Value is changed to: "+wait.st);
wait.valchange("Hello World");
}catch(Exception e){}
}
}

Download Source Code