Java Sleeping A Thread:

When running thread suddenly calls the sleep() method then immediately it will enter into sleeping state. sleep() method is called as

the thread will come out from sleeping state to ready state if time expires or if sleeping thread got interrupted. sleep() method by default throws an exception, so we have to call sleep() method within a try and catch block. Let's see an example for better clarity:

Example

class SleepDemo extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
SleepDemo sd1=new SleepDemo();
SleepDemo sd2=new SleepDemo();
sd1.start();
sd2.start();
}
}

Output

1
1
2
2
3
3
4
4

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment