Reputation: 11
I want the second print to happen after 2 seconds.
System.out.println("First print.");
//I want the code that makes the next System.out.println in 2 seconds.
System.out.println("This one comes after 2 seconds from the println.");
Upvotes: 0
Views: 5122
Reputation: 521093
You should use Thread#sleep:
Causes the currently executing thread to sleep
Note that you should use try-catch
block around the call to Thread.sleep()
because another Thread could interrupt main()
while it's sleeping. In this case, it's not necessary to catch it because there is only one Thread active, main()
.
try {
Thread.sleep(2000)
catch (InterruptedException e) {
System.out.println("main() Thread was interrupted while sleeping.");
}
Upvotes: 2
Reputation: 22233
Just use Thread#sleep:
System.out.println("First print.");
Thread.sleep(2000);//2000ms = 2s
System.out.println("This one comes after 2 seconds from the println.");
Note that Thread.sleep
can throw an InterruptedException
, so you will need a throws
clause or a try-catch
, like:
System.out.println("First print.");
try{
Thread.sleep(2000);//2000ms = 2s
}catch(InterruptedException ex){
}
System.out.println("This one comes after 2 seconds from the println.");
or:
public void something() throws InterruptedException {
System.out.println("First print.");
Thread.sleep(2000);//2000ms = 2s
System.out.println("This one comes after 2 seconds from the println.");
}
Upvotes: 5
Reputation: 801
If you want your java code to sleep for 2 sec you can use the sleep function in Thread:
Thread.sleep(millisec);
The millisec argument is how many milliseconds you want to sleep f.ex:
1 sec = 1000 ms
2 sec = 2000 ms
and so on..
So your code will be something like this:
System.out.println("First print.");
try {
Thread.sleep(2000); //2 secs
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("This one comes after 2 seconds from the println.");
(the try-catch is needed because sometimes it will throw a excpetion if the SecurityManager dont allow the thread to sleep but dont worry, thats will never happen..)
-Max
Upvotes: 1
Reputation: 9775
Thread.currentThread().sleep(2000); //2000 milliseconds = 2 seconds
Upvotes: 1
Reputation: 8928
try {
Thread.sleep(2000); //2 secs
catch (InterruptedException e) {
}
Upvotes: 3