Share on Google+Share on Google+

Java Sleep Thread

Ads
This Java tutorial illustrates how to use Java static sleep() method in Thread. We will create an java Sleep Thread example using the Thread with sleep method.

  • Java Thread sleep() is a static method.
  • It sleeps the thread for the given time in milliseconds.
  • It is used to delay the thread.
  • It is used in Applet or GUI programming for animation


Java Sleep Thread Example
public class sleep1 extends Thread {

	public sleep1(String s) {
	super(s);
	}
	@Override
	public void run() {
		for (int i = 1; i <= 4; i++) {
			if (i % 2 == 0) {
				try {
					Thread.sleep(1000);
					System.out.println("Thread is  sleeping  "
							+ Thread.currentThread());
				} catch (Exception e) {
				}
			} 
			else {
				System.out.println("Thread is not  sleeping  "
						+ Thread.currentThread());
			}
		}
	}

	public static void main(String[] args) {
      sleep1 s1=new sleep1("mythread1");
      sleep1 s2=new sleep1("mythread2");
      s1.start();
      s2.start();
	}
}

Output

Thread is not sleeping Thread[mythread1,5,main] Thread is not sleeping Thread[mythread2,5,main] Thread is sleeping Thread[mythread2,5,main] Thread is sleeping Thread[mythread1,5,main] Thread is not sleeping Thread[mythread1,5,main] Thread is not sleeping Thread[mythread2,5,main] Thread is sleeping Thread[mythread1,5,main] Thread is sleeping Thread[mythread2,5,main]

Advertisements

Ads

Posted on: November 7, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.

Ads

Advertisement