package com.zy.core.utils; import java.util.concurrent.*; public class TimeoutExecutor { public static T executeWithTimeout(Callable task, long timeout, TimeUnit unit) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Future future = executor.submit(task); try { return future.get(timeout, unit); } catch (TimeoutException e) { future.cancel(true); // 中断任务 throw new TimeoutException("Task timed out"); } finally { executor.shutdownNow(); } } }