溫馨提示×

Java倒計時器的代碼實現(xiàn)有哪些技巧

小樊
82
2024-09-03 15:09:16
欄目: 編程語言

在Java中,實現(xiàn)倒計時器的方法有很多,以下是一些常見的技巧:

  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();
                }
            }
        });
    }
}

這些技巧可以根據(jù)你的需求進行組合和修改。注意,當在生產(chǎn)環(huán)境中使用倒計時器時,請確保正確處理線程中斷和異常。

0