实现倒计时的4种方式

使用TimeUnit实现倒计时

public static void countDown(int sec) throws InterruptedException {
    while (sec > 0) {
        System.out.println(sec + "s");
        TimeUnit.SECONDS.sleep(1);
        sec--;
    }
}

使用Timer实现倒计时

public static void countDown(int second) {
    long start = System.currentTimeMillis();
    final long end = start + second * 1000;
    final Timer timer = new Timer();
    timer.schedule(new TimerTask()
                   {
                       public void run()
                       {
                           long show = end - System.currentTimeMillis();
                           long s = show / 1000 % 60;
                           System.out.println(s + "s");
                       }
                   },0,1000);

    timer.schedule(new TimerTask()
                   {
                       public void run()
                       {
                           timer.cancel();
                       }

                   }, new Date(end));
}

使用Thread.sleep()实现倒计时

public static void countDown(int seconds) throws InterruptedException {
    while(seconds > 0){
        System.out.println(seconds + "s");
        Thread.sleep(1000L);
        seconds--;
    }
}

使用CountDownLatch实现倒计时

CountDownLatch是同步工具类。有一个计数器,初始值为指定数值,每调用countDown()一次计数器减1,直至0,调await()方法结束。

public static void countDown(int seconds) throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(seconds);
    while(seconds > 0){
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() ->{
            latch.countDown();
        }
                  ).start();
        System.out.println(seconds);
        seconds--;
    }
    latch.await();
}

 

posted @ 2023-11-26 10:49  残城碎梦  阅读(155)  评论(0)    收藏  举报