我正在尝试在 Java 中做一些事情,我需要在一段时间循环中等待/延迟几秒钟。
while (true) {
if (i == 3) {
i = 0;
}
ceva[i].setSelected(true);
// I need to wait here
ceva[i].setSelected(false);
// I need to wait here
i++;
}
我想构建一个步进音序器。
如何在 Java 中延迟?
如果要暂停,请使用 :java.util.concurrent.TimeUnit
TimeUnit.SECONDS.sleep(1);
要睡一秒钟或
TimeUnit.MINUTES.sleep(1);
睡一分钟。
由于这是一个循环,这带来了一个固有的问题——漂移。每次你运行代码然后睡觉时,你都会偏离运行,比如说,每秒。如果这是一个问题,则不要使用 .sleep
此外,在控制方面不是很灵活。sleep
对于每秒或延迟一秒运行任务,我强烈建议使用 a 和 or 或 .ScheduledExecutorService
scheduleAtFixedRate
scheduleWithFixedDelay
例如,要每秒运行一次该方法 (Java 8):myTask
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
在Java 7中:
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
myTask();
}
}, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
Use Thread.sleep(1000)
;
1000
is the number of milliseconds that the program will pause.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Use this:
public static void wait(int ms)
{
try
{
Thread.sleep(ms);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
然后,您可以在任何位置调用此方法,例如:
wait(1000);
模板简介:该模板名称为【如何在 Java 中延迟?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Java】栏目查找您需要的精美模板。