问题描述
建立一个线程,要求是:实时显示系统时间,而且设定在一定时间之后停止时间显示的格式是yyyy-mm-ddhh:mm:ss
解决方案
解决方案二:
看满不满足你的要求吧packagetest;importjava.text.SimpleDateFormat;importjava.util.Calendar;importjava.util.Date;importjava.util.GregorianCalendar;publicclassTest{publicstaticvoidmain(String[]args){Timetime=newTime(30);time.start();}}classTimeextendsThread{privateSimpleDateFormatsdf=newSimpleDateFormat("yyyy-mm-ddhh:mm:ss");privateDateend_time;publicTime(){}//分钟的偏移量publicTime(intoffset){Calendarcal=newGregorianCalendar();cal.add(GregorianCalendar.MINUTE,offset);end_time=cal.getTime();}@Overridepublicvoidrun(){while(end_time.compareTo(newDate())!=0){StringformattedDate=sdf.format(newDate());System.out.println(formattedDate);try{Thread.sleep(1000);}catch(Exceptione){e.printStackTrace();}}}}
解决方案三:
packageday;importjava.text.SimpleDateFormat;importjava.util.Calendar;importjava.util.GregorianCalendar;importjava.util.Timer;importjava.util.TimerTask;publicclassShowTime{privatefinalstaticTimertimer=newTimer();privatefinalstaticSimpleDateFormatsdf=newSimpleDateFormat("yyyy-mm-ddhh:mm:ss");publicstaticvoidshowTime(){timer.schedule(newTimerTask(){intt=60;//设置一分钟计时publicvoidrun(){Calendarcal=newGregorianCalendar();System.out.println(sdf.format(cal.getTime())+"t还有:"+t+"秒");t=t-1;if(t<0){timer.cancel();//一分钟后,停止计时}}},0,1000);//以秒为单位}publicstaticvoidmain(String[]args){showTime();}}