java实现倒计时器

0. 倒计时器应用

倒计时器经常应用于各种需要进行计时的场景中。

1. 使用Timer方法

public class CountDownTimer {

    private Timer timer;
    private int remainingSeconds; // 倒计时时长

    public CountDownTimer(int remainingSeconds) {
        this.remainingSeconds = remainingSeconds;
        timer = new Timer();
    }

    public void start(int interval) {
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println("倒计时:" + remainingSeconds + "秒!");
                remainingSeconds -= interval; // 每秒减少的时间
                if(remainingSeconds < 0) {
                    timer.cancel();
                    System.out.println("倒计时结束!!!");
                }
            }
        }, 0, 1000);
    }

    public static void main(String[] args) {
        CountDownTimer timer = new CountDownTimer(10);
        timer.start(1);
    }
}

2. 使用ScheduledExecutor实现

public class CountdownTimer {

	private int seconds;
	
	public CountdownTimer(int seconds) {
		this.seconds = seconds;
	}
	
	public void start() {
		ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
		executor.scheduleAtFixedRate(new Runnable() {
			public void run() {
				System.out.println(seconds);
				seconds--;
				if (seconds < 0) {
					executor.shutdown();
				}
			}
		}, 0, 1, TimeUnit.SECONDS);
	}
	
	public static void main(String[] args) {
		CountdownTimer timer = new CountdownTimer(10);
		timer.start();
	}
}

3. 使用CountDownLatch实现

public class CountdownTimer {
	private int seconds;
	
	public CountdownTimer(int seconds) {
		this.seconds = seconds;
	}
	
	public void start() throws InterruptedException {
		final CountDownLatch latch = new CountDownLatch(seconds);
		for (int i = 0; i < seconds; i++) {
			final int count = i;
			new Thread(new Runnable() {
				public void run() {
					System.out.println(seconds - count);
					latch.countDown();
				}
			}).start();
		}
		latch.await();
	}
	
	public static void main(String[] args) throws InterruptedException {
		CountdownTimer timer = new CountdownTimer(10);
		timer.start();
	}
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值