Java Thread Wait and Signal Example

Here we will discuss the wait() method in Java. It is the most common question of interviews.

Here is the table content of the article will we will cover this topic.

1. What is the wait() method in Java?
2. How wait() method works?
3. wait(long timeoutMillis) method?

What is the wait() method in Java?

The wait() method is defined in Object class which is the super most class in Java. This method tells the calling thread (Current thread) to give up the lock and go to sleep until some other thread enters the same monitor and calls notify() or notifyAll(). It is a final method, so we can't override it.

Let's have a look at code.

public final void wait() throws InterruptedException  {         wait(0L); }

How wait() method works?

1. The wait() method is used for interthread communication. In Inter-thread communication, the synchronized threads can communicate with each other. As you know in synchronized block or method, only one thread can enter(acquire the lock). By use of wait() method a thread is paused(release lock) running in its critical section and another thread can enter (acquire the lock) in the same critical section.
So that multiple threads can communicate between the thread by use of usewait()andnotify(). You can tell one thread to stop working (By wait() method) from another thread based upon some condition, later you can notify it to start processing again(By notify() or notifyAll() method).

2. The wait() method is tightly integrated with the synchronization lock, using a feature not available directly from the synchronization mechanism.

3. Unlike sleep()method, the wait()method, the thread goes in waiting state and it won't come back automatically until we call the notify()or notifyAll().

Let's understand with an example

Let's say a user wants to print some pages in the printer. So, we are creating two threads, one thread for print the pages and another thread for add the pages in the printer.
If the number of papers in the printer is less than the number of entered input, then we will call wait() method for the thread, meanwhile, another thread will add more pages in the printer and notify the current thread by notify() method.

class Printer  {  	// Initial 100 paper are set in Printer 	int noOfPaper = 100;   	// Synchronized the method for inter-thread communication  	synchronized void printingPages(int pages)  	{  		System.out.println("Printing the Pages");  		for(int i = 0; i < 100; i++) 		{ 			// Printing Pages 		} 		 		 		// If balance number of Papers are less than user input  		// then wait for addPages() synchronized method    		// and printing will resume after that 		if (this.noOfPaper < pages) {   			System.out.println("Number of Papers in printer are less");  			try  			{  				System.out.println("Waiting..."); 				wait();  			}  			catch (Exception e)  			{  				 			}  		}  		 		System.out.println("After called notify() method number of Paper : " +	this.noOfPaper);  		System.out.println("Printing process complete"); 		  	}   	synchronized void addPages(int noOfPages)  	{  		// Adding more Papers in Printer;  		this.noOfPaper += noOfPages;  		// After adding the paper in printer. Notify the Paused thread;  		notify();  	}  }   public class MainClass {   	public static void main(String args[])  	{  		Printer printer = new Printer();  		// create two new thread and start them simultaneously  		//First thread for print the pages 		new Thread()  		{  			@Override 			public void run()  			{  				// User want to print 120 pages 				printer.printingPages(120);  			}  		}.start();  		 		// Second thread for Add pages in printer 		new Thread() {  			@Override 			public void run()  			{  				// Add 100 more pages in Printer 				printer.addPages(100);  			}  		}.start();  	}  }        

Output: Printing the Pages
Number of Papers in printer are less
Waiting…
After called notify() method number of Paper : 200
Printing process complete

wait() method in Java

Object class has three variances of the wait() method. We will discuss them one by one.

1. wait() method: This method doesn't take any argument; it waits indefinitely for any other thread to call notify() or notifyAll() method on the object to wake up the current thread. We had discussed this method in the above example.

2. wait(long timeoutMillis) method: The other two variances put the current thread in wait for a specific amount of time before they wake up.

wait(long timeoutMillis) method

It is another variance of the wait() method. By use of this method the calling thread (Current thread) to give up the lock and go to sleep until a certain amount of time has elapsed or calls notify() or notifyAll().

public final native void wait(long timeoutMillis) throws InterruptedException;

Here timeoutMillis the maximum time to wait, in milliseconds. You can't send the negative value as a parameter.
If you are using negative value then compiler throws IllegalArgumentException.
If the current thread is not the owner of the object's monitor then compiler throws IllegalMonitorStateException.
If any thread interrupted the current thread before or while the current thread was waiting. then compiler throws InterruptedException.

class Printer  {  	// Initial 100 paper are set in Printer 	int noOfPaper = 100;   	// Synchronized the method for inter-thread communication  	synchronized void printingPages(int pages)  	{  		System.out.println("Printing the Pages");  		for(int i = 0; i < 100; i++) 		{ 			// Printing Pages 		} 		 		// If balance number of Papers are less than user input  		// then wait for addPages() synchronized method    		// and printing will resume after that 		if (this.noOfPaper < pages)  		{  			System.out.println("Number of Papers in printer are less");  			try  			{  				System.out.println("Waiting for 5 Second..."); 				wait(5000);  			}  			catch (Exception e)  			{  				 			}  		}  		System.out.println("After called notify() method number of Paper : " +	this.noOfPaper);  		System.out.println("Printing process complete"); 		  	}   	synchronized void addPages(int noOfPages)  	{  		// Adding more Papers in Printer;  		this.noOfPaper += noOfPages;  		// After adding the paper in printer. Notify the Paused thread;  		notify();  	}  }   public class MainClass  {  	public static void main(String args[])  	{  		Printer printer = new Printer();  		// create two new thread and start them simultaneously  		// First thread for print the pages 		new Thread()  		{  			@Override 			public void run()  			{  				// User want to print 120 pages 				printer.printingPages(120);  			}  		}.start();  		 		// Second thread for Add pages in printer 		new Thread()  		{  			@Override 			public void run()  			{  				// Add 100 more pages in Printer 				try  				{ 					Thread.sleep(10000); 				} catch (InterruptedException e) { 					// TODO Auto-generated catch block 					e.printStackTrace(); 				} 				printer.addPages(100);  			}  		}.start();  	}  }        

Output: Printing the Pages
Number of Papers in printer are less
Waiting for 5 Second…
After called notify() method number of Paper : 100
Printing process complete

childsentile.blogspot.com

Source: https://javagoal.com/wait-method-in-java/

0 Response to "Java Thread Wait and Signal Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel