public static void function() {
// 代码1
// 代码2
// 代码3
}
如果代码2执行时间过长则不再执行(代码2没有抛出TimeoutException,只是没按照规定时间执行完),继续执行后面的代码3该如何实现呢?
下面是代码超时功能的一种实现
public class Timeout {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService exec = Executors.newFixedThreadPool(1);
Callable<Integer> call = new Callable<Integer>() {
public Integer call() throws Exception {
Thread.sleep(1000 * 5);// 耗时操作
return 1;
}
};
try {
Future<Integer> future = exec.submit(call);
int ret = future.get(1000 * 1, TimeUnit.MILLISECONDS); // 任务处理超时时间设为 1 秒
System.out.println("任务执行结果:" + ret);
} catch (TimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
exec.shutdown();
}
}
但这种方法的问题是新启动了一个线程,并没有阻塞,也就是我的代码3可能先于Timeout执行完,顺序不满足预期,前辈有什么好办法呢?
米琪卡哇伊
相关分类