Asked By
anonymous
7060 points
N/A
Posted on - 09/18/2011
Could someone explain me with example those function
Notify()
NotifyAll()
Wait()
Sleep()
And
Yield()
Answered By
user91
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();
b.start();
synchronized(b) Â Â //thread got lock
{
System.out.println("I am calling wait method");
b.wait();
System.out.println("I got notification");
}
System.out.println(b.total);
}
}
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++)
{
total=total+i;
}
System.out.println("I am giving notification call");
notify(); Â Â //thread releases lock again
}
}
}
Â
output:
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).
Â