java wait one second code example

Example 1: java delay

Syntax :
=========================================================
	Thread.sleep(1000); // 1000 milliseconds..          |
=========================================================
int i=0;
for(;;){
	Thread.sleep(2000); // set time delay to 2 seconds.. 
  	System.out.println(i++); // output : every output will display after 2 seconds..   	
}

Example 2: java pause 1 second

//deprecated in main thread:
try {
  Thread.sleep(1000);//time is in ms (1000 ms = 1 second)
} catch (InterruptedException e) {e.printStackTrace();}

//please use bellow instead:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
  @Override
  public void run() {
    //what you want to do
  }
}, 1000);//wait 1000ms before doing the action

Example 3: java wait a second

// Java program to demonstrate 
// sleep() method of TimeUnit Class 
  
import java.util.concurrent.*; 
  
class WaitASecond { 
    public static void main(String args[]) 
    { 
        // Get time to sleep 
        long timeToSleep = 0L; 
  
        // Create a TimeUnit object 
        TimeUnit time = TimeUnit.SECONDS; 
  
        try { 
  
            System.out.println("Going to sleep for "
                               + timeToSleep 
                               + " seconds"); 
  
            // using sleep() method 
            time.sleep(timeToSleep); 
  
            System.out.println("Slept for "
                               + timeToSleep 
                               + " seconds"); 
        } 
  
        catch (InterruptedException e) { 
            System.out.println("Interrupted "
                               + "while Sleeping"); 
        } 
    } 
}

Tags:

Java Example