当两个方法执行时间不一致的时候,如何使被调用的方法超时就返回null

当两个方法执行时间不一致的时候,如何使被调用的方法超时就返回null

问题描述:

假设现在有一个A方法执行时间不确定,我们现在用B方法调用A方法。要求B方法的执行时间限制为3秒,超过时间就返回默认值,如何实现

long startTime=System.nanoTime();  //获取开始时间

doSomeThing(); //测试的代码段

long endTime=System.nanoTime(); //获取结束时间

System.out.println("程序运行时间: "+(endTime-startTime)+"ns");

public class Say implements Callable { @Override public Boolean call() throws Exception { Thread.sleep(5000L); return true; } }


private static boolean methodB() { Boolean flag; ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); Future future = executorService.submit(new Say()); try { flag = future.get(3000L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { return false; } catch (ExecutionException e) { return false; } catch (TimeoutException e) { return false; } finally { executorService.shutdown(); } return flag; }