Java - Comment retarder quelques secondes

Java - Comment retarder quelques secondes

En Java, nous pouvons utiliserTimeUnit.SECONDS.sleep() ouThread.sleep() pour retarder quelques secondes.

1. TimeUnit

JavaDelayExample.java

package com.example;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class JavaDelayExample {

    public static void main(String[] args) {

        try {

            System.out.println("Start..." + new Date());
            // delay 5 seconds
            TimeUnit.SECONDS.sleep(5);
            System.out.println("End..." + new Date());

            // delay 0.5 second
            //TimeUnit.MICROSECONDS.sleep(500);

            // delay 1 minute
            //TimeUnit.MINUTES.sleep(1);

        } catch (InterruptedException e) {
            System.err.format("IOException: %s%n", e);
        }


    }

}

sortie

Start...Mon Apr 08 21:42:55 SRET 2019
End...Mon Apr 08 21:43:00 SRET 2019

2. Thread.sleep

JavaDelayExample2.java

package com.example;

import java.util.Date;

public class JavaDelayExample2 {

    public static void main(String[] args) {

        try {

            System.out.println("Start..." + new Date());
            // delay 5 seconds
            Thread.sleep(5000);
            System.out.println("End..." + new Date());

        } catch (InterruptedException e) {
            System.err.format("IOException: %s%n", e);
        }


    }

}