依赖
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1.1-jre</version>
</dependency>
代码
package com.ds.demo;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import java.util.concurrent.*;
/**
* @author : mark
* @desc :
* @since : 2021/5/27 10:36
*/
public class Tests {
//声明一个线程池
static ExecutorService executor = new ThreadPoolExecutor(5, 20,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
//超时控制
static SimpleTimeLimiter simpleTimeLimiter = SimpleTimeLimiter.create(executor);
//方法返回
static Object result = null;
//超时时间
static final Integer TIME_OUT = 5;
public static Object callTimeOut() {
try {
result = simpleTimeLimiter.callWithTimeout(new Callable<Object>() {
@Override
public Object call() throws Exception {
//超时业务
//String name = HttpRequest.get("127.0.0.1:5000/scoreCard/m6").execute().body();
return name;
}
}, TIME_OUT, TimeUnit.SECONDS);
System.out.println("正常调用" + result);
} catch (Exception e) {
System.out.println("异常调用");
} finally {
executor.shutdown();
}
return result;
}
public static void main(String[] args) {
System.out.println("222222" + callTimeOut());
}
}