java返回超时 怎么处理_java函数执行超时强制返回

import java.lang.reflect.Method;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.FutureTask;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.TimeoutException;

/**

* @author Gergul 函数执行超时

* @Notice: 不能执行同名而且参数数量相同的函数!!

* @Usage: RunningTimeout.Run(类对象, 方法名字, 参数列表, 超时时间 单位毫秒);

*/

public class RunningTimeout implements Callable

{

private Object ower = null;

private String sMethodName = null;

// private Class[] paramTypes;

private Object[] paramValues;

// 外部接口

public static Object Run(Object ower, String sMethodName,

Object[] paramValues, long timeout) throws InterruptedException,

ExecutionException, TimeoutException

{

RunningTimeout rt = new RunningTimeout();

return rt._run(ower, sMethodName, paramValues, timeout);

}

// 不允许new

private RunningTimeout()

{

}

//

private Object _run(Object ower, String sMethodName, Object[] paramValues,

long timeout) throws InterruptedException, ExecutionException,

TimeoutException

{

this.ower = ower;

this.sMethodName = sMethodName;

this.paramValues = paramValues;

// 关键代码

ExecutorService executor = Executors.newSingleThreadExecutor();

FutureTask future = (FutureTask)executor.submit(this);

executor.execute(future);

return future.get(timeout, TimeUnit.MILLISECONDS);

}

// 真正做事的地方

@Override

public Object call() throws Exception

{

// TODO Auto-generated method stub

Method[] methods = ower.getClass().getDeclaredMethods();

int n = methods.length;

for (int i = 0; i < n; i++)

{

if (sMethodName.equals(methods[i].getName()))

{

Method thisMethod = methods[i];

if (thisMethod.getParameterTypes().length == paramValues.length)

{// 检查参数的数量是否相同

return methods[i].invoke(ower, paramValues);

}

}

}

throw new Exception("No this method.");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值