Java等待下一次打印

时间:2013-06-23 11:13:35

标签: java timer

我希望第二次打印在2秒后发生。

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.");

5 个答案:

答案 0 :(得分:5)

只需使用Thread#sleep

System.out.println("First print.");
Thread.sleep(2000);//2000ms = 2s
System.out.println("This one comes after 2 seconds from the println.");

请注意,Thread.sleep可以抛出InterruptedException,因此您需要throws子句或try-catch,例如:

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.");

或:

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.");
}

答案 1 :(得分:3)

try {
    Thread.sleep(2000); //2 secs
catch (InterruptedException e) {
}

答案 2 :(得分:2)

您应该使用Thread#sleep

  

导致当前正在执行的线程休眠

请注意,您应该在调用try-catch时使用Thread.sleep()阻止,因为另一个线程可能在其正在休眠时中断main()。在这种情况下,没有必要捕获它,因为只有一个Thread活动,main()

try {
    Thread.sleep(2000)
catch (InterruptedException e) {
    System.out.println("main() Thread was interrupted while sleeping.");
}

答案 3 :(得分:1)

Thread.currentThread().sleep(2000); //2000 milliseconds = 2 seconds

答案 4 :(得分:1)

如果您希望Java代码休眠2秒,可以使用Thread中的sleep函数:

Thread.sleep(millisec);

millisec参数是你要睡多少毫秒f.ex:

1 sec = 1000 ms
2 sec = 2000 ms
and so on..

所以你的代码将是这样的:

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.");

(需要try-catch,因为如果SecurityManager不允许线程进入睡眠状态,有时它会抛出一个激活,但不要担心,那将永远不会发生..)
-max