写完js倒计时,突然想用java实现倒计时,写了三种实现方式
一:设置时长的倒计时;
二:设置时间戳的倒计时;
三:使用java.util.Timer类实现的时间戳倒计时
代码如下:
1 package timer; 2 3 import java.util.Calendar; 4 import java.util.Date; 5 import java.util.Timer; 6 import java.util.TimerTask; 7 8 /** 9 * java演示倒计时 10 * 11 */ 12 public class TimeTest { 13 public static int time = 60 * 60 * 60; 14 public static Calendar c; 15 public static long endTime; 16 public static Date date; 17 public static long startTime; 18 public static long midTime; 19 20 public static void main(String[] args) { 21 c = Calendar.getInstance(); 22 c.set(2017, 4, 17, 0, 0, 0);// 注意月份的设置,0-11表示1-12月 23 // c.set(Calendar.YEAR, 2017); 24 // c.set(Calendar.MONTH, 4); 25 // c.set(Calendar.DAY_OF_MONTH, 17); 26 // c.set(Calendar.HOUR_OF_DAY, 0); 27 // c.set(Calendar.MINUTE, 0); 28 // c.set(Calendar.SECOND, 0); 29 endTime = c.getTimeInMillis(); 30 date = new Date(); 31 startTime = date.getTime(); 32 midTime = (endTime - startTime) / 1000; 33 34 // time1();//方式一 35 time2();// 方式二 36 // time3();//方式三 37 } 38 39 /** 40 * 方式三: 使用java.util.Timer类进行倒计时 41 */ 42 private static void time3() { 43 Timer timer = new Timer(); 44 timer.schedule(new TimerTask() { 45 public void run() { 46 midTime--; 47 long hh = midTime / 60 / 60 % 60; 48 long mm = midTime / 60 % 60; 49 long ss = midTime % 60; 50 System.out.println("还剩" + hh + "小时" + mm + "分钟" + ss + "秒"); 51 } 52 }, 0, 1000); 53 } 54 55 /** 56 * 方式二: 设定时间戳,倒计时 57 */ 58 private static void time2() { 59 60 while (midTime > 0) { 61 midTime--; 62 long hh = midTime / 60 / 60 % 60; 63 long mm = midTime / 60 % 60; 64 long ss = midTime % 60; 65 System.out.println("还剩" + hh + "小时" + mm + "分钟" + ss + "秒"); 66 try { 67 Thread.sleep(1000); 68 69 } catch (InterruptedException e) { 70 e.printStackTrace(); 71 } 72 } 73 } 74 75 /** 76 * 方式一: 给定时长倒计时 77 */ 78 private static void time1() { 79 while (time > 0) { 80 time--; 81 try { 82 Thread.sleep(1000); 83 int hh = time / 60 / 60 % 60; 84 int mm = time / 60 % 60; 85 int ss = time % 60; 86 System.out.println("还剩" + hh + "小时" + mm + "分钟" + ss + "秒"); 87 } catch (InterruptedException e) { 88 e.printStackTrace(); 89 } 90 } 91 92 } 93 }
运行结果:
time1()结果:
time2()结果:
time3()结果:
时间: 2024-11-08 20:10:24