#
Junjie
4 天以前 6daf900a09adcca981f620744bf89851654d88e0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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();
        }
    }
 
}