threads

Sleep Thread

With this example we are going to demonstrate how to make a Thread sleep. In short, to make a Thread sleep you should:

  • Call sleep(long millis) API method of Thread. The method causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
  • In the example, we are using a main() method, where in a loop we call the Thread to sleep for one millisecond.
  • Every time before the thread sleeps we print out the time so as to check the time between the thread sleeps.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;

import java.util.Date;

public class SleepThreadExample {
	
	public static void main(String[] args) {
		
		try {

			for (int i = 0; i < 5; i++) {
				System.out.println(i + " " + new Date());
				Thread.sleep(1000);
			}
			
		}
		catch (InterruptedException ie) {
			System.out.println("Thread interrupted!" + ie);
		}
		
	}

}

Output:

0 Tue Oct 18 23:56:37 EEST 2011
1 Tue Oct 18 23:56:38 EEST 2011
2 Tue Oct 18 23:56:39 EEST 2011
3 Tue Oct 18 23:56:40 EEST 2011
4 Tue Oct 18 23:56:41 EEST 2011

  
This was an example of how to make a Thread sleep in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button