如何在Java中进行延迟?

我正在尝试用Java做一些事情,我需要在while循环中等待/延迟几秒钟

while(真){
如果(i==3){
i=0;
}
ceva[i].setSelected(真);
//我需要在这里等
ceva[i].setSelected(假);
//我需要在这里等
i++;
}

我想构建一个step sequencer,我是Java新手。有什么建议吗

如果要暂停,请使用java.util.concurrent.TimeUnit

时间单位。秒。睡眠(1);

睡一秒钟或几秒钟

时间单位。分钟。睡眠(1);

睡一会儿

由于这是一个循环,因此存在一个固有的问题-漂移。每次你运行代码然后睡觉的时候,你都会有点偏离运行的方向,比如说,每秒钟。如果这是一个问题,那么不要使用睡眠

此外,sleep在控制方面也不是很灵活

对于每秒钟或每延迟一秒钟运行一个任务,我将强烈地推荐一个ScheduledExecutorServicescheduleAtFixedRatescheduleWithFixedDelay

例如,要每秒运行方法myTask(Java 8):

公共静态void main(字符串[]args){
final ScheduledExecutorService executorService=Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(应用程序::myTask,0,1,时间单位为秒);
}
私有静态void myTask(){
System.out.println(“运行”);
}

在Java 7中:

公共静态void main(字符串[]args){
final ScheduledExecutorService executorService=Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(新的Runnable(){
@凌驾
公开募捐{
myTask();
}
},0,1,时间单位为秒);
}
私有静态void myTask(){
System.out.println(“运行”);
}

发表评论