Difference between wait(1000) and sleep(1000) in java with example

The sleep method is used when the thread has to be put aside for a fixed amount of time.

Ex: sleep(1000), puts the thread aside for exactly one second.

The wait method is used to put the thread aside for up to the specified time. It could wait for a much lesser time if it receives a notify() or notifyAll() call.

Ex: wait(1000), causes a wait of up to one second.

The method wait() is defined in the Object and the method sleep() is defined in the class Thread.


package com.example.TestApp;public class SleepingThread{    public static void main( String[] args ) throws InterruptedException    {        System.out.println( "Hello World!" );        Thread t1 = new Thread(new Producer());        t1.start();        Thread.sleep(50000); //will sleep exactly 5 seconds        t1.join();         System.out.println( "End of Main Thread" );    }}class Producer implements Runnable {    public void run() {        try {         synchronized(this) {                    wait(50000); //will wait up to 5 seconds                    System.out.println( "End of Producer1 Thread" );            }              } catch(InterruptedException e) {     }  }}