实现倒计时的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 @   残城碎梦  阅读(109)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
历史上的今天:
2021-11-26 常用的JVM参数
2021-11-26 Java程序生成Heap dump几种方式
2021-11-26 关于linux下,ls vi等命令失效的解决方法(配置下环境变量出现问题)
点击右上角即可分享
微信分享提示