Java – sleep() method in Thread

sleep():

  • It is a static method define in Thread class.
  • It is used to stop the thread execution for specified number of milliseconds.
  • sleep() method throws InterruptedException
class Default
{
            public static void main(String[] args)
            {
                        First f = new First();
                        Second s = new Second();
                        f.start();
                        s.start();
            }
}
class First extends Thread
{
            public void run()
            {
                        for (int i=1 ; i<=10 ; i++)
                        {
                                    System.out.println(“First : ” + i);
                                    try{
                                                Thread.sleep(1000);
                                    }catch(Exception e){ }
                        }
            }
}
class Second extends Thread
{
            public void run()
            {
                        for (int i=1 ; i<=10 ; i++)
                        {
                                    System.out.println(“Second : ” + i);
                                    try{
                                                Thread.sleep(1000);
                                    }catch(Exception e){ }
                        }
            }
}
Scroll to Top