import java.util.concurrent.ExecutorService;
@Service
public class TestService{
private ExecutorService executorService;
//第一步:定义一个外部线程池
@PostConstruct
public void init() {
//定义线程池
int poolSize = Runtime.getRuntime().availableProcessors() * 2;
executorService = new ThreadPoolExecutor(poolSize, poolSize,
0, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1024), // 使用有界队列,避免OOM
new ThreadPoolExecutor.DiscardPolicy());
}
//第二步:定义一个内部线程池类,
//通过设置时间段,来监控回调函数s在一定时间内未返回,则认为此函数异常,此时抛出该异常,释放当前线程,避免因为某个线程一直不释放导致整体线程池出问题
private static class Wait {
//线程池
private static ForkJoinPool pool = new ForkJoinPool();
//参数:①s:回调函数,即执行逻辑 ②要等待时间的数字:1,2,10等等 ③时间的类型:时分秒等等
//返回值:是参数s对应函数的返回值
public static <T> T wait(Supplier<T> s, int t, TimeUnit unit) throws Exception{
CompletableFuture<T> f = CompletableFuture.supplyAsync(s, pool);
return f.get(t, unit);
}
}
//第三步:编写具体的代码执行逻辑
//具体的执行代码逻辑
public void queryDataNew(){
try{
//若20分钟内,该方法未返回,则认为出现异常
List<String> resultList = Wait.wait(() -> {
//如果需要外部参数,则使用AtomicReference类的get和set方法即可
List<String> userList = new ArrayList<>();
userList.add("1");
userList.add("2");
userList.add("3");
//代码逻辑
...
return userList;
},20, TimeUnit.MINUTES);
return resultList;
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException("自定义异常:"+e.getMessage());
}finally{
//无论程逻辑是否报错,都需要执行的逻辑,可无
}
}
//第四步:测试的整体代码逻辑
public void test(){
executorService.submit(() -> {
this.queryDataNew();
});
System.out.println("方法调用");
}
}