// So either after 1000 miliseconds, current thread will wake up, or after we call

//t. interrupt() method.

Example: Create a class
FirstThread.java as below.

1

2

3

4

5

6

7

8

9

10

11

12

packageorg.arpit.java2blog.thread;

publicclassFirstThreadimplementsRunnable{

publicvoidrun()

{

System.out.println("Thread is running");

}

}

Create main class named
ThreadSleepExampleMain.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

packageorg.arpit.java2blog.thread;

publicclassThreadSleepExampleMain{

publicstaticvoidmain(Stringargs[])

{

FirstThread ft=newFirstThread();

Threadt=newThread(ft);

t.start();

longstartTime=System.currentTimeMillis();

try{

// putting thread on sleep

Thread.sleep(1000);

}catch(InterruptedExceptione){

e.printStackTrace();

}

longendTime=System.currentTimeMillis();

longtimeDifference=(endTime-startTime);

System.out.println("Time difference between before and after sleep call: "+timeDifference);

}

}

When you run above program, you will get following output.

Thread is running
Time difference between before and after sleep call: 1001

You can see there is a delay of 1000 milliseconds (1 sec). As mentioned earlier, its accuracy depends on system timers and schedulers.

How Thread Sleep Works

Thread.sleep() works with thread scheduler to pause current thread execution for specific period of time. Once thread wait period is over, the thread’s state is changed to runnable again and it is available for further execution for CPU.