在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(); } } }); } }
这些技巧可以根据你的需求进行组合和修改。注意,当在生产环境中使用倒计时器时,请确保正确处理线程中断和异常。