在Java中,实现重试机制并防止短时间内多次尝试,可以使用一个循环结合 Thread.sleep 来实
现。以下是一个示例代码,展示了如何在重试时加入冷却时间:
1. 使用 Thread.sleep 实现重试机制
public class RetryExample {
private static final int MAX_ATTEMPTS = 50;
private static final int SLEEP_TIME = 2000; // 冷却时间为2秒
public static void main(String[] args) {
retryWithCoolDown();
}
public static void retryWithCoolDown() {
int attempts = 0;
while (attempts < MAX_ATTEMPTS) {
try {
// 尝试执行某个操作
if (performOperation()) {
System.out.println("操作成功");
break; // 操作成功,退出循环
} else {
System.out.println("操作