본문으로 건너뛰기

Java sleep으로 몇 초 지연

sleep()으로 몇초간 지연시키는 방법입니다.

1. Thread.sleep()

Thread.sleep()은 인자로 전달된 milliseconds 만큼 지연을 시킵니다.

아래와 같이 for문에서 sleep()을 사용하여 1초 간격으로 어떤 내용을 반복시킬 수 있습니다.

import java.time.LocalDateTime;

public class Example {

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {
// do something
System.out.println("Repeat something a second: " + LocalDateTime.now());

// sleep 1 sec
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Output:

Repeat something a second: 2022-12-18T07:02:29.597338655
Repeat something a second: 2022-12-18T07:02:30.602866655
Repeat something a second: 2022-12-18T07:02:31.603284843
Repeat something a second: 2022-12-18T07:02:32.603680324
Repeat something a second: 2022-12-18T07:02:33.604054891
Repeat something a second: 2022-12-18T07:02:34.604425094
Repeat something a second: 2022-12-18T07:02:35.604797318
Repeat something a second: 2022-12-18T07:02:36.605118127
Repeat something a second: 2022-12-18T07:02:37.605380575
Repeat something a second: 2022-12-18T07:02:38.605769026

2. TimeUnit.SECONDS.sleep()

TimeUnit.SECONDS.sleep(n)는 n초만큼 지연시킵니다.

아래와 같이 for문에서 1초 간격으로 어떤 내용을 실행시킬 수 있습니다.

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

public class Example {

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {
// do something
System.out.println("Repeat something a second: " + LocalDateTime.now());

// sleep 1 sec
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Output:

Repeat something a second: 2022-12-18T07:03:03.268886303
Repeat something a second: 2022-12-18T07:03:04.274193344
Repeat something a second: 2022-12-18T07:03:05.274714798
Repeat something a second: 2022-12-18T07:03:06.275109217
Repeat something a second: 2022-12-18T07:03:07.275408939
Repeat something a second: 2022-12-18T07:03:08.275809369
Repeat something a second: 2022-12-18T07:03:09.276096450
Repeat something a second: 2022-12-18T07:03:10.276403300
Repeat something a second: 2022-12-18T07:03:11.276657782
Repeat something a second: 2022-12-18T07:03:12.277101324