写完js倒计时,突然想用java实现倒计时,写了三种实现方式
一:设置时长的倒计时;
二:设置时间戳的倒计时;
三:使用java.util.timer类实现的时间戳倒计时
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
package timer;
import java.util.calendar;
import java.util.date;
import java.util.timer;
import java.util.timertask;
/**
* java演示倒计时
*
*/
public class timetest {
public static int time = 60 * 60 * 60 ;
public static calendar c;
public static long endtime;
public static date date;
public static long starttime;
public static long midtime;
public static void main(string[] args) {
c = calendar.getinstance();
c.set( 2017 , 4 , 17 , 0 , 0 , 0 ); // 注意月份的设置,0-11表示1-12月
// c.set(calendar.year, 2017);
// c.set(calendar.month, 4);
// c.set(calendar.day_of_month, 17);
// c.set(calendar.hour_of_day, 0);
// c.set(calendar.minute, 0);
// c.set(calendar.second, 0);
endtime = c.gettimeinmillis();
date = new date();
starttime = date.gettime();
midtime = (endtime - starttime) / 1000 ;
// time1();//方式一
time2(); // 方式二
// time3();//方式三
}
/**
* 方式三: 使用java.util.timer类进行倒计时
*/
private static void time3() {
timer timer = new timer();
timer.schedule( new timertask() {
public void run() {
midtime--;
long hh = midtime / 60 / 60 % 60 ;
long mm = midtime / 60 % 60 ;
long ss = midtime % 60 ;
system.out.println( "还剩" + hh + "小时" + mm + "分钟" + ss + "秒" );
}
}, 0 , 1000 );
}
/**
* 方式二: 设定时间戳,倒计时
*/
private static void time2() {
while (midtime > 0 ) {
midtime--;
long hh = midtime / 60 / 60 % 60 ;
long mm = midtime / 60 % 60 ;
long ss = midtime % 60 ;
system.out.println( "还剩" + hh + "小时" + mm + "分钟" + ss + "秒" );
try {
thread.sleep( 1000 );
} catch (interruptedexception e) {
e.printstacktrace();
}
}
}
/**
* 方式一: 给定时长倒计时
*/
private static void time1() {
while (time > 0 ) {
time--;
try {
thread.sleep( 1000 );
int hh = time / 60 / 60 % 60 ;
int mm = time / 60 % 60 ;
int ss = time % 60 ;
system.out.println( "还剩" + hh + "小时" + mm + "分钟" + ss + "秒" );
} catch (interruptedexception e) {
e.printstacktrace();
}
}
}
}
|
运行结果:
time1()结果:
time2()结果:
time3()结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/heizai002/p/6862625.html