java倒計時三種簡單實現方式
阿新 • • 發佈:2017-09-26
idt 使用 instance too rgs 設置 private block ace
寫完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()結果:
標簽: java, java倒計時, 計時器, 倒計時java倒計時三種簡單實現方式