public class RetryUtils { private static final long BASE_WAIT_MS = 500; private static final int MAX_RETRY = 5; @FunctionalInterface public interface RetryTask { T execute() throws Exception; } public static T retry(RetryTask task) throws Exception { int attempt = 0; while (attempt < MAX_RETRY) { try { return task.execute(); } catch (Exception e) { attempt++; if (attempt >= MAX_RETRY) { System.out.println("最终失败: " + e.getMessage()); throw e; } long waitTime = BASE_WAIT_MS * (1L << attempt); System.out.println("尝试执行 #" + attempt + "... 失败"); System.out.println("等待: " + waitTime + "ms"); try { Thread.sleep(waitTime); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie); } } } throw new IllegalStateException("重试逻辑异常"); } public static void main(String[] args) throws Exception { RetryUtils.retry(() -> { System.out.println("尝试执行"); throw new RuntimeException("模拟失败"); }); } }