java程序执行超时
public class MethodTest {/** * 要测试的方法 * @return */public String test() {try {Thread.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}return "test";}}?
public static void main(String[] args) {MethodTest test = new MethodTest();Callable<String> call = getCallable("test", test, (Object[])null);String result = testFuture(call, 1, TimeUnit.MILLISECONDS);System.out.println(result);}/** * * @param <T> * @param methodName 要执行的方法名 * @param obj方法所在的对象 * @param args方法的参数 * @return */public static <T> Callable<T> getCallable(final String methodName,final Object obj,final Object ... args){Callable<T> call = new Callable<T>() {@SuppressWarnings("unchecked")public T call() throws Exception {Method method= obj.getClass().getMethod(methodName, (Class[])null);return (T) method.invoke(obj,args);}};return call;}/** * * @param <T> * @param call * @param timeOut 超时时间 * @param unit时间单位 * @return */public static <T> T testFuture(Callable<T> call,int timeOut,TimeUnit unit){ExecutorService executorService = Executors.newSingleThreadExecutor();FutureTask<T> futureTask = new FutureTask<T>(call);executorService.execute(futureTask);T result = null;try {result = futureTask.get(timeOut, unit);} catch (InterruptedException e) {futureTask.cancel(true);e.printStackTrace();} catch (ExecutionException e) {futureTask.cancel(true);e.printStackTrace();} catch (TimeoutException e) {futureTask.cancel(true);e.printStackTrace();} finally {executorService.shutdown();}return result;}? 1 楼 Technoboy 2011-05-25 引用