Java倒计时的三种方法

Java倒计时的三种方法

package daojishi;
import java.util.Date;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
/**
 * @author 演示倒计时
 *
 */
public class daojishi{
     
	 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[] arg) {
     
		 /*Date date=new Date();
		 System.out.println(date);*/
		 c=Calendar.getInstance();
		 c.set(2020,10,11,0,0,0);
		 endTime=c.getTimeInMillis();
		 date=new Date();
		 startTime=date.getTime();
		 midTime=(endTime-startTime)/1000;
		 //time1();
		 //time2();
		 time3();
	 }
	 /*
	  * 方法一:给定时长倒计时
	  */
	 private static void time1() {
     
		 while(time>0) {
     
			 time--;
			 try {
     
				 Thread.sleep(1000);
				 int h=time/60/60%60;
				 int m=time/60%60;
				 int s=time%60;
				 System.out.println("还剩"+h+"小时"+m+"分钟"+s+"秒");

			 }catch(InterruptedException e) {
     
				 e.printStackTrace();
			 }
		 }
	 }
	 /*
	  * 方法二:设定时间戳,倒计时
	  */
	 private static void time2() {
     
		 while (midTime>0) {
     
			 midTime--;
			 long h=midTime/60/60%60;
			 long m=midTime/60%60;
			 long s=midTime%60;
			 System.out.println("还剩"+h+"小时"+m+"分钟"+s+"秒");
			 try {
     
				 Thread.sleep(1000);
			 }
			 catch(InterruptedException e) {
     
				 e.printStackTrace();
			 }
		 }
	 }
	 /*
	  * 方法三:使用java.util.Timer类进行倒计时
	  */
	 private static void time3() {
     
		 Timer timer=new Timer();
		 timer.schedule(new TimerTask() {
     
			 public void run() {
     
				 midTime--;
				 long h=midTime/60/60%60;
				 long m=midTime/60%60;
				 long s=midTime%60;
				 System.out.println("还剩"+h+"小时"+m+"分钟"+s+"秒");
			 }
		 },0,1000);
	 }
}

Java倒计时的三种方法_第1张图片

你可能感兴趣的