java怎样做倒计时,Java 中怎么实现倒计时
Java codepublic class 倒計時時鐘 {
//小時
private int hours;
//分鐘
private int min;
//秒
private int second;
public 倒計時時鐘(int hours,int min,int second) {
this.hours = hours;
this.min = min;
this.second = second;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public int getSecond() {
return second;
}
public void setSecond(int second) {
this.second = second;
}
}
public class 倒計時 implements Runnable{
private 倒計時時鐘 clock;
private long time;
public 倒計時(倒計時時鐘 clock) {
this.clock = clock;
//將時間換算成秒
time = clock.getHours()*60*60+clock.getMin()*60+clock.getSecond();
}
public void run() {
while(time >= 0) {
try {
Thread.sleep(1000);
time -= 1;//時間減去一秒
clock.setHours((int)time/(60*60));
clock.setMin((int)(time/60)%60);
clock.setSecond((int)time % 60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//return clock;
}
public 倒計時時鐘 getTime() {
return clock;
}
public static void main(String [] args) {
倒計時時鐘 clock = new 倒計時時鐘(0,10,0);
倒計時 jishi = new 倒計時(clock);
顯示 show = new 顯示(jishi.getTime());
//顯示 show = new 顯示();
new Thread(show).start();
new Thread(jishi).start();
}
}
class 顯示 implements Runnable {
private 倒計時時鐘 clock;
public 顯示(倒計時時鐘 clock) {
this.clock = clock;
}
public void run() {
while(clock.getHours() != 0 ||
clock.getMin() != 0 ||
clock.getSecond() != 0) {
try {
System.out.println(String.format("%02d",clock.getHours())+
":"+String.format("%02d",clock.getMin())+
":"+String.format("%02d",clock.getSecond()));
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
總結
以上是生活随笔為你收集整理的java怎样做倒计时,Java 中怎么实现倒计时的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C4D使用注意事项
- 下一篇: Java如何自定义异常?