Home » Java programming language

Java Object Class final void wait() method with Example

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

Object Class final void wait()

  • This method is available in java.lang.Object.wait().
  • This method causes the current thread to wait 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.

Syntax:

    final void wait(){
    }

Parameter(s):

We don't pass any object 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() 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();

        synchronized(t2) {

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

            // By calling wait() causes the current thread to 
            // wait until execution of another thread
            t2.wait();

            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 < 100; ++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
Main thread trying to call wait()
Thread t2 starts notification
Thread t2 trying to given notification
Main Thread get notification here
4950





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.