Skip to content
← Back to Community
How can I delay something in Java?
Profile icon
PythoNinja

I want something to delay in Java, but I don't know how....
Thanks!

Answered by Coder100 [earned 5 cycles]
View Answer
Voters
Profile icon
PythoNinja
Comments
hotnewtop
Profile icon
Coder100

Use the thread.sleep method.
https://www.tutorialspoint.com/java/lang/thread_sleep_millis.htm

import java.lang.Thread; public class Main { public static void main(String[] args) { System.out.println("Hi"); Thread.sleep(1000); System.out.println("hi after 1 second"); } }
Profile icon
PythoNinja

@Coder100 It says "Unhandled exception type InterruptedExecption" when I did the stuff.

Profile icon
Coder100

@PythoNinja send repl that's not supposed to happen

Profile icon
PythoNinja

@Coder100 Now it says this instead:
Capture

Profile icon
Coder100

@PythoNinja

public class main(String[] args) throws InterruptedException

change that line to that

Profile icon
PythoNinja

@Coder100 Okay, I changed my Main Class into the public class main, and now, it says
image
for some reason.

Profile icon
Coder100

uh can you invite me you did it wrong @PythoNinja

Profile icon
PythoNinja

@Coder100 alright

Profile icon
cuber1515

I believe you do Thread.sleep() and in the parenthesis put the milliseconds, so if you wanted to do it for 1 second, then: Thread.sleep(1000).