package com.zy.core.utils;
|
|
import java.util.concurrent.*;
|
|
public class TimeoutExecutor {
|
|
public static <T> T executeWithTimeout(Callable<T> task, long timeout, TimeUnit unit) throws Exception {
|
ExecutorService executor = Executors.newSingleThreadExecutor();
|
Future<T> 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();
|
}
|
}
|
|
}
|