[英]How can I interrupt method execution by time?
假设方法A
调用方法B
方法A
控制方法B
执行时间并将其中断,例如60秒(例如方法B
可以挂起)?
您可以使用ExecutorService
异步运行任务,获得Future
,使您可以在完成任务后获取任务的结果。 Future
上有一个get
方法,您可以调用该方法以等待超时的答案。 如果超时,则尝试通过在Future
上调用cancel
来取消任务。
ExecutorService executorService = Executors.newSingleThreadExecutor();
// Callable that has a run() method that executes the task
Callable<String> callable = ...;
// Submit the task for execution
Future<String> future = executorService.submit(callable);
try {
String result = future.get(30, TimeUnit.SECONDS);
System.out.println("Result: " + result);
}
catch (TimeoutException e) {
System.out.println("Timeout");
future.cancel(true);
}
并发API还有很多,请参见包java.util.concurrent
。
你能描述你到底想要什么吗? 只需停止执行方法,就可以使用return, System.exit()
,最后停止VM。 按时间,只需检查时间并从方法返回即可。 另外,您可以尝试一些反思技巧...顺便说一下,如果您用更多的言语描述您需要什么,我将为您提供帮助。
尝试:
public static void wait(int n){
long time0,time1;
time0=System.currentTimeMillis();
do{
time1=System.currentTimeMillis();
}
while (time1-time0<n);
}
我认为这可行。 如果调用此方法,请以希望程序等待的时间(以毫秒为单位)作为参数传递。
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.