在Java中,實現(xiàn)倒計時器的方法有很多,以下是一些常見的技巧:
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();
}
}
});
}
}
這些技巧可以根據(jù)你的需求進行組合和修改。注意,當在生產(chǎn)環(huán)境中使用倒計時器時,請確保正確處理線程中斷和異常。