Java Sleep Thread


 

Java Sleep Thread

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.

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]

Ads