Java

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

小樊
82
2024-09-03 15:09:16
栏目: 编程语言

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

  1. 使用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();
            }
        }
    }
}
  1. 使用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);
    }
}
  1. 使用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();
            }
        }
    }
}
  1. 使用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();
                }
            }
        });
    }
}

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

0
看了该问题的人还看了