public class Countdown2 {
private volatile int lin;
private int curSec;
public Countdown2(int lin) throws InterruptedException{
/*记录倒计时时间*/
this.lin = lin;
/*记录倒计时当下时间*/
this.curSec = lin;
System.out.println("最后倒计时: " + lin + "秒");
/*此处存在缺陷,需要手动创建线程池*/
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleAtFixedRate(new Task(),0,1,TimeUnit.SECONDS );
//暂停本线程
TimeUnit.SECONDS.sleep(lin);
exec.shutdown();
System.out.println("Game over!!");
}
private class Task implements Runnable{
@Override
public void run() {
System.out.println("倒计时: " + --curSec + "秒");
}
}
public static void main(String[] args) throws InterruptedException{
new Countdown2(20);
}
}