这篇文章主要介绍了java编程倒计时实现的三个示例,三种实现方法,具有一定参考价值,需要的朋友可以了解下。
实现Java编程中倒计时的方法有许多,下面我们通过三个示例来简单了解下它的实现过程。
1.简易方式实现
/**
* @see
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月18日 上午3:10:13
* @version V1.0
* Description: 倒计时简易实现,只用单线程
*/
import java.util.*;
import java.util.concurrent.*;
public class CountDown {
private int limitSec;
public CountDown(int limitSec) throws InterruptedException{
this.limitSec = limitSec;
System.out.println("Count from "+limitSec);
while(limitSec > 0){
System.out.println("remians "+ --limitSec +" s");
TimeUnit.SECONDS.sleep(1); //设置倒计时间隔
}
System.out.println("Time is out");
}
//Test
public static void main(String[] args) throws InterruptedException {
new CountDown(100); //倒计时起始时间,多少秒
}
}2.使用ScheduleExecutor实现
/**
* @see
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月18日 上午2:14:43
* @version V1.0
* Description: 倒计时实现方式1:使用ScheduledExecutor实现
* 使用两个线程;
*/
import java.util.concurrent.*;
public class CountDown1 {
private volatile int limitSec ; //记录倒计时时间
private int curSec; //记录倒计时当下时间
public CountDown1(int limitSec) throws InterruptedException{
this.limitSec = limitSec;
this.curSec = limitSec;
System.out.println("count down form "+limitSec);
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleAtFixedRate(new Task(),0,1,TimeUnit.SECONDS);
TimeUnit.SECONDS.sleep(limitSec); //暂停本线程
exec.shutdownNow();
System.out.println("Time out!");
}
private class Task implements Runnable{
public void run(){
System.out.println("Time remains "+ --curSec +" s");
}
}
//Test
/* public static void main(String[] args) throws InterruptedException{
new CountDown1(10);
}*/
}3.使用java.util.Timer实现
传统驾校预约方式步骤繁琐,效率低下,随着移动互联网科技和5G的革新,驾校考试领域迫切需要更加简洁、高效的预约方式,便捷人们的生活。因此设计基于微信小程序的驾校预约系统,改进传统驾校预约方式,实现高效的驾校学校预约。 采用腾讯提供的小程序云开发解决方案,无须服务器和域名。驾校预约管理:开始/截止时间/人数均可灵活设置,可以自定义客户预约填写的数据项驾校预约凭证:支持线下到场后校验签到/核销/二维码自
0
立即学习“Java免费学习笔记(深入)”;
/**
* @see
* @author Al_assad yulinying_1994@outlook.com
* @date 2016年10月18日 上午2:47:44
* @version V1.0
* Description: 倒计时实现方式2:使用java.uitl.Timer实现
* 使用两个线程
*/
import java.util.*;
import java.util.concurrent.TimeUnit;
public class CountDown2 {
private int limitSec;
private int curSec;
public CountDown2(int limitSec) throws InterruptedException{
this.limitSec = limitSec;
this.curSec = limitSec;
System.out.println("count down from "+limitSec+" s ");
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
System.out.println("Time remians "+ --curSec +" s");
}
},0,1000);
TimeUnit.SECONDS.sleep(limitSec);
timer.cancel();
System.out.println("Time is out!");
}
//Test
/* public static void main(String[] args) throws InterruptedException{
new CountDown2(10);
}*/
}总结
以上就是Java实现倒计时的方法详解的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号