Home » Java programming language

Java Object Class final void wait(long ms) method with Example

Java Object class final void wait(long ms) method: Here, we are going to learn about the final void wait(long ms) method of Object class with its syntax and example.
Submitted by Preeti Jain, on June 28, 2019

Object Class final void wait(long ms)

  • This method is available in java.lang.Object.wait(long ms).
  • This method causes the current thread to wait for a specified amount of time until another thread notification by calling notify() or notifyAll() method of the object.
  • This method throws an InterruptedException when other thread interrupted current thread.
  • This method can't override because it is final.
  • The time will be given in the method is of milliseconds.

Syntax:

    final void wait(long ms){
    }

Parameter(s):

We can pass an object(How long a thread has to wait i.e. we have to mention time in milliseconds) as a parameter in the method of the Object class.

Return value:

The return type of this method is void that means this method returns nothing after execution.

Java program to demonstrate example of Object Class wait(long ms) method

import java.lang.Object;

public class Thread1 {
    public static void main(String[] args) throws InterruptedException {

        // Create an object of Thread2

        Thread2 t2 = new Thread2();

        // By calling start() so Thread start() will exceute
        t2.start();

        Thread.sleep(1000);

        synchronized(t2) {

            System.out.println("Main thread trying to call wait()");

            // By calling wait() causes the current thread to wait 
            // for 1000 milliseconds until another   thread notification
            t2.wait(1000);

            System.out.println("Main Thread get notification here");
            System.out.println(t2.total);

        }

    }
}

class Thread2 extends Thread {

    int total = 0;

    public void run() {

        synchronized(this) {

            System.out.println("Thread t2 starts notification");

            for (int i = 0; i < 50; ++i) {

                total = total + i;
            }

            System.out.println("Thread t2 trying to given notification");

            this.notify();

        }

    }
}

Output

D:\Programs>javac Thread1.java

D:\Programs>java Thread1
Thread t2 starts notification
Thread t2 trying to given notification
Main thread trying to call wait()
Main Thread get notification here
1225



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.