Home Tutorial Java Core Java Thread : sleep() method

 
 

Share on Google+Share on Google+
Java Thread : sleep() method
Posted on: October 20, 2012 at 12:00 AM
Advertisement
In this section we are going to describe sleep() method with example in java thread.

Java Thread : sleep() method

In this section we are going to describe sleep() method with example in java thread.

sleep() method :

Suppose you want to stop your thread for a specific time period, you can use sleep() method. The Thread.sleep() method pauses the current thread for a specified time period.

sleep(long millis) : It puts the current executing thread to sleep for a given number of milliseconds.
millis - It defines the length of time in milliseconds.

sleep(long millis, int nanos) : It puts the current executing thread to sleep for a given number of milliseconds and nanoseconds.
millis - It defines the length of time in milliseconds.
nanos - It defines additional nanoseconds to sleep. It ranges 0-999999.

Example :

public class ThreadSleep implements Runnable {

	Thread thread;

	public void run() {

		System.out.println(Thread.currentThread().getName() + " ");
		try {
			/*
			 * sleep for the specified number of milliseconds and nanoseconds
			 */
			System.out.println("Calling sleep() method...");
			Thread.sleep(100, 100);
		} catch (Exception e) {
			System.out.println(e);
		}

	}

	public static void main(String[] args) throws Exception {
		Thread thread1 = new Thread(new ThreadSleep());
		Thread thread2 = new Thread(new ThreadSleep());

		thread1.start();
		thread2.start();
		thread1.join();
		System.out.println(thread1.getName() + " commpleted");
		thread2.join();
		System.out.println(thread2.getName() + " commpleted");
	}
}

Output :

Thread-0 
Calling sleep() method...
Thread-1 
Calling sleep() method...
Thread-0 commpleted
Thread-1 commpleted
Advertisement

Related Tags for Java Thread : sleep() method :


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 20, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com