Could someone explain those notify(),notifyAll()….function?

Asked By 7060 points N/A Posted on -

Could someone explain me with example those function


Answered By 0 points N/A #80448

Could someone explain those notify(),notifyAll()….function?


Hey hi Rajibhossan

These all functions are related to the threads. First let's discuss about notify(), notifyAll() and wait() functions.

wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).

notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The 
highest priority thread will run first. 
Read the following program carefully and you will be cleared about these functions.
package thread;
public class ThreadA
public static void main(String[]args)throws InterruptedException
ThreadB b =new ThreadB();
synchronized(b)     //thread got lock
System.out.println("I am calling wait method");
System.out.println("I got notification");
class ThreadB extends Thread
int total=0;
public void run()
synchronized (this)//.thread got lock
System.out.println("I am starting calculation");
for(int i=0;i<=1000;i++)
System.out.println("I am giving notification call");
notify();    //thread releases lock again
I am calling wait method
I am starting calculation
I am giving notification call
I got notification
500500 Now let's discuss about sleep() and yield() functions. sleep() function is used for suspending a thread for a period of time.
Example: Suppose we have a thread named Thread. We will use the sleep method like Thread.sleep(1000) In round brackets you will mention the time period for which you want the thread to be suspended. yield() – This static method is essentially used to notify the system that the current thread is willing to "give up the CPU" for a while.
The general idea is that The thread scheduler will select a different thread to run instead of the current one.
Basically Thread.yield() calls the Windows API call Sleep(0).


Login/Register to Answer

Related Questions