如何使Java延迟几秒钟? [英] How to make java delay for a few seconds?
本文介绍了如何使Java延迟几秒钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,我都有这段代码。我想将程序延迟几秒钟,然后显示正在扫描...
Hey all I have this code. I want to delay my program for a few seconds and display "scanning..."
这就是我的所有内容。如果(i == 1){
try {},它可以编译但不会延迟任何东西
Here's what I have. This compiles but doesn't delay anything
if (i==1){
try {
Thread.sleep(1);
} catch (InterruptedException ie)
{
System.out.println("Scanning...");
}
}
预先感谢
我显然是int i = 1
thanks in advance I have int i = 1 before obviously
推荐答案
如果要暂停,请使用 java.util。 parallel.TimeUnit
:
TimeUnit.SECONDS.sleep(1);
睡觉一秒钟或十分钟
TimeUnit.MINUTES.sleep(10);
或线程睡眠
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
另请参见官方文档
TimeUnit.SECONDS .sleep()
将调用 Thread.sleep
。唯一的区别是可读性,在不明显的持续时间内使用TimeUnit可能更容易理解。
TimeUnit.SECONDS.sleep()
will call Thread.sleep
. The only difference is readability and using TimeUnit is probably easier to understand for non obvious durations.
但是如果您想解决问题
int timeToWait = 10; //second
System.out.print("Scanning")
try {
for (int i=0; i<timeToWait ; i++) {
Thread.sleep(1000);
System.out.print(".")
}
} catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
}
这篇关于如何使Java延迟几秒钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文