Wait in java program

wait() method in Java

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

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

Читайте также:  Радиус

What is the wait() method in Java?

The wait() method is defined in the 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 the code.

public final void wait() throws InterruptedException

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 a synchronized block or method, only one thread can enter(acquire the lock). By use of the 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 use wait() and notify(). You can tell one thread to stop working (By the 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 the sleep() method, in the wait() method, the thread goes into 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 printing the pages and another thread for adding the pages to the printer.
If the number of papers in the printer is less than the number of entered inputs, then we will call the 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 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) gives up the lock and goes 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.
Using a negative value then the compiler throws IllegalArgumentException.
If the current thread is not the owner of the object’s monitor then the compiler throws IllegalMonitorStateException.
If any thread interrupted the current thread before or while the current thread was waiting. then the 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

Difference between wait and sleep in java

Defined in different classes

The sleep() method is defined in the Thread class and it is a static method so we can call it by Thread class.

The wait() method exists in the Object class and it is a non-static method so we can call it by the object.

Context

The wait() method is called only from the synchronized context that is synchronized block or synchronized method.
The sleep() method can be called from any context.

Call

As we discuss the wait() method is defined in the Object class. So, it operates on an Object and we can call the wait() method only by the thread object which we want to make wait.

A sleep() method operates on the current thread and when we call the sleep() method, the JVM assumes we want to sleep the thread in which the method is placed.

State change

When we use the sleep() method, it pauses the execution of the current thread and moves that thread to the TIMED_WAITING state. After the competition of waiting time, the thread moves again in a RUNNABLE state.

Where wait() method also pauses the execution of the thread and moves that thread to the WAITING state.

Lock

The sleep() method doesn’t release the lock on an object and it holds the lock for a specific time or until interrupted.

The wait() method releases the lock on an object and gives another thread a chance to acquire the lock and enter a synchronized method or block.

Wake up

When a thread is paused, it is in the TIMED_WAITING state after calling the sleep() method. It can’t be woken up. It wakes up when the given time expires. If any thread interrupts in between it throws InterruptedException.

When a thread is paused, it is in a WAITING state after calling the wait() method. it can be woken up by other threads by calling notify() or notifyAll() methods on the same lock.

Method available

The sleep() method is available in the Thread class only. We can use the sleep() method by use of the Thread class or we can extend the Thread class in our own class.

The wait() method is available in the Object class. It means, the wait() method is available in all classes. We can call it by use of the object of the class.

Execution

If we call the sleep() method by use of the thread object it will pause the current thread, not the thread that is used to call. Suppose we are calling thread1.sleep(), some programmers misunderstood the concept. It will also pause the current thread.

In each class wait() method is available, so the object has each wait() method for inter-communication between threads.

Exception

The sleep() method throws InterruptedException if any thread has interrupted the current thread and IllegalArgumentException if the value of arguments is negative.

The wait() method throws an exception If the current thread is not the owner of the object’s monitor then the compiler throws IllegalMonitorStateException.
If any thread interrupted the current thread before or while the current thread was waiting. then the compiler throws InterruptedException.

Источник

Java wait seconds or delay Java program for few secs

Delay java program by few seconds

In this post, we will see how to delay java program for few secs or wait for seconds for java program to proceed further.

We need to delay a java programs in many situation where we want to wait for some other task to finish.

There are multiple ways to delay execution of java program or wait for seconds to execute it further.

Using Thread.sleep

Sleep method causes current thread to pause for specific duration of time.We can use Thread’s class sleep static method delay execution of java program.

Here is sample code to the same.

Please note that Unit of time is milliseconds for sleep method, that’s why we have passed 5000 for 5 secs delay.

Sleep method is not always accurate as it depends on system timers and schedulers.

Using TimeUnit.XXX.sleep method

You can use java.util.concurrent.TimeUnit to sleep for specific duration of time.

For example:
To sleep for 5 mins, you can use following code

To sleep for 10 sec, you can use following code

Internally TimeUnit.SECONDS.sleep will call Thread.sleep method. Only difference is readability.

Using ScheduledExecutorService

You can also use ScheduledExecutorService which is part of executor framework. This is most precise and powerful solution to pause any java program.

I would strongly recommend to use ScheduledExecutorService in case you want to run the task every secs or few secs delay.

For example:
To run the task every second, you can use following code.

executorService . scheduleAtFixedRate ( DelayFewSecondsJava : : runTask , 0 , 1 , TimeUnit . SECONDS ) ;

executorService.scheduleAtFixedRate(DelayFewSecondsJava::runTask, 0, 1, TimeUnit.SECONDS);
Here DelayFewSecondsJava is classname and runTask is method name of that class.

Running the task each second
Running the task each second
Running the task each second
Running the task each second

Frequently asked questions on Java wait seconds

How to wait for 5 seconds in java?

You can simply use below code to wait for 5 seconds.

How to wait for 1 seconds in java?

You can simply use below code to wait for 1 seconds.

How to pause for 5 seconds in java?

Pause and wait are synonyms here, so you can simply use below code to pause for 5 seconds.

That’s all how to delay java program for few seconds or how to wait for seconds in java.

Was this post helpful?

You may also like:

Get Thread Id in Java

ArrayBlockingQueue in java

How to print even and odd numbers using threads in java

Why wait(), notify() And notifyAll() methods are in Object Class

Custom BlockingQueue implementation in java

Difference between Runnable and Callable in java

Java Runnable example

Java Executor framework tutorial with example

Java ExecutorCompletionService

Share this

Author

Get Thread Id in Java

Get Thread Id in Java

Table of ContentsGet Thread Id in JavaGet Thread Id of Current Running ThreadGet Thread id of Multiple Threads In this article, we will learn to get thread id of a running thread in Java. An Id is a unique positive number generated at the time of thread creation. This id remains unchanged during the lifetime […]

ArrayBlockingQueue in java

ArrayBlockingQueue in java

Table of ContentsWhat is BlockingQueueArrayBlockingQueueFeaturesConstructorsMethodsUsage ScenariosImplementation CodeSummary In this article, we will understand the Java concurrent queue, BlockingQueue. We will then go deep into it’s one of the implementation, ArrayBlockingQueue. What is BlockingQueue BlockingQueue interface was introduced in Java 5 under concurrent APIs and it represents a thread-safe queue in which elements can be added […]

How to print even and odd numbers using threads in java

Table of ContentsProblemSolution 1Print even and odd numbers using threads in javaSolution 2: Using remainder In this post, we will see how to print even and odd numbers using threads in java. see also: How to print sequence using 3 threads in java Problem You are given two threads. You need to print odd numbers […]

wait(),notify() and notifyAll() in java

Why wait(), notify() And notifyAll() methods are in Object Class

In this post, we will see why wait(), notify() And notifyAll() methods are in Object Class And Not in Thread Class. This is one of the most asked java multithreading interview questions. You might know that wait(), notify() And notifyAll() Methods are in Object class and do you know the reason for the same? Let’s […]

Custom BlockingQueue in java

Custom BlockingQueue implementation in java

In this post, we will see how to create your own custom BlockingQueue. This is one of the most asked java interview questions. You need to implement your own BlockingQueue. This question helps interviewer to get your understanding of multithreading concepts. Here is simple implementation of BlockingQueue. We will use array to store elements in […]

Difference between Runnable and Callable in java

Difference between Runnable and Callable in java

Runnable and Callable interface both are used in the multithreading environment.Callable is available in java.util.concurrent.Callable package and Runnable in java.lang.Thread. Difference between Runnable and Callable interface in java Runnable was introduced in java 1.0 version While Callable is an extended version of Runnable and introduced in java 1.5 to address the limitation of Runnable. Runnable […]

Источник

Оцените статью