This page topics close

The sleep() method of Thread class is used to sleep a thread for the specified period of time.

  • Syntax of sleep() Method

    • public static void sleep(long milliseconds) throws InterruptedException;

    • public static void sleep(long milliseconds, int nano) throws InterruptedException;


    Example of sleep method

    
    //example of sleeping the user thread
    class UserThread extends Thread
    {
    	public void run()
    	{
    		try
    		{
    			for(int i=1;i<=10;i++)
    			{
    				System.out.println("value of i ="+i);
    				Thread.sleep(1000);
    			}
    		}catch(InterruptedException e)
    		{
    			e.printStackTrace();
    		}
    	}
    
    	public static void main(String[] args) {
    		UserThread t=new UserThread();
    		t.start();
    	}
    }

    Output:
    value of i =1
    value of i =2
    value of i =3
    value of i =4
    value of i =5
    value of i =6
    value of i =7
    value of i =8
    value of i =9
    value of i =10

What next?

The next topic is Joining a thread

Share this page