Java倒计时器的代码实现有哪些技巧

   2024-09-30 7860
核心提示:在Java中,实现倒计时器的方法有很多,以下是一些常见的技巧:使用Thread.sleep()方法:public class CountdownTimer {public st

在Java中,实现倒计时器的方法有很多,以下是一些常见的技巧:

使用Thread.sleep()方法:
public class CountdownTimer {    public static void main(String[] args) {        int seconds = 10;        for (int i = seconds; i >= 0; i--) {            System.out.println(i);            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}
使用ScheduledExecutorService
import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class CountdownTimer {    public static void main(String[] args) {        int seconds = 10;        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);        executor.scheduleAtFixedRate(() -> {            if (seconds > 0) {                System.out.println(seconds--);            } else {                executor.shutdown();            }        }, 0, 1, TimeUnit.SECONDS);    }}
使用CountDownLatch
import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;public class CountdownTimer {    public static void main(String[] args) {        int seconds = 10;        CountDownLatch latch = new CountDownLatch(seconds);        for (int i = 0; i< seconds; i++) {            new Thread(() -> {                try {                    latch.await();                    System.out.println(seconds--);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }).start();            latch.countDown();            try {                TimeUnit.SECONDS.sleep(1);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}
使用CompletableFuture
import java.util.concurrent.CompletableFuture;import java.util.concurrent.TimeUnit;public class CountdownTimer {    public static void main(String[] args) {        int seconds = 10;        CompletableFuture.runAsync(() -> {            while (seconds >= 0) {                System.out.println(seconds--);                try {                    TimeUnit.SECONDS.sleep(1);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        });    }}

这些技巧可以根据你的需求进行组合和修改。注意,当在生产环境中使用倒计时器时,请确保正确处理线程中断和异常。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号