JAVA后台时间等待
JAVA中实现让程序等待一段时间的方法,JAVA中想让代码等待一段时间再继续执行,可以通过让当前线程睡眠一段时间的方式。
1.通过线程的sleep方法
try {
Thread.currentThread().sleep(1000);//等待1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
在需要程序等待的地方加入这个语句,实现让程序等待,这里的参数1000是以毫秒为单位,即这语句可以让程序等待1秒。
2.通过Thread.sleep
try {
for(int i=1;i<6;i++) {
Thread.sleep(2000);//等待2秒
}
} catch (InterruptedException e){
e.printStackTrace();
}
3.TimeUnit类里的sleep方法
TimeUnit.DAYS.sleep(1);//天
TimeUnit.HOURS.sleep(1);//小时
TimeUnit.MINUTES.sleep(1);//分
TimeUnit.SECONDS.sleep(1);//秒
TimeUnit.MILLISECONDS.sleep(1000);//毫秒
TimeUnit.MICROSECONDS.sleep(1000);//微妙
TimeUnit.NANOSECONDS.sleep(1000);//纳秒
try {
for(int i=1;i<6;i++) {
TimeUnit.SECONDS.sleep(3);//等待3秒
}
} catch (InterruptedException e){
e.printStackTrace();
}
TimeUnit类提供的方法,其实底层调用的也是Thread类的sleep方法,让程序进行等待。只不过他在上层根据时间单位进行了封装,如上图,共有7种可以选择,可以方便的选择自己需要的时间单位进行使用。
html页面时间等待
1.通过html meta实现
跳转...释义:content="3,url=IndexServlet" 中3是指延迟3秒。
2.通过setInterval实现
通过setInterval函数,来周期性的更新倒计时间,同时更新到页面。页面上的显示效果是3 2 1,然后跳转到index.html
3
setInterval(jump,1000);
var sec = 3;
function jump(){
sec--;
if(sec > 0){
document.getElementById('remainSeconds').innerHTML = sec;
}else{
window.location.href = 'index.html';
}
}
通过setTimeout执行一个延迟函数来达到跳转的目的
setTimeout(jump,3000);
function jump(){
window.location.href='IndexServlet';
}
3.通过setTimeout实现
通过setTimeout 函数,来周期性的更新倒计时间,同时更新到页面。页面上的显示效果是3 2 1,然后跳转到index.html
3
var sec = 3;
function jump(){
sec--;
if(sec > 0){
document.getElementById('remainSeconds').innerHTML = sec;
setTimeout(this.jump,1000);
}else{
window.location.href = 'index.html';
}
}
setTimeout(jump,1000);