开发者社区> 问答> 正文

如何实现代码超时功能?

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执行完,顺序不满足预期,前辈有什么好办法呢?

展开
收起
蛮大人123 2016-03-13 11:42:25 2285 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    写了个小例子,可以简单实现你的要求

    public class Main {
    
        public static void main(String[] args) throws InterruptedException {
            ExecutorService es = Executors.newFixedThreadPool(1);
            es.execute(new Runnable() {
                @Override
                public void run() {
                    int count = 7;
                    while (count > 0) {
                        System.out.println(1);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // 退出执行
                            System.out.println("interrupt, then quit");
                            return;
                        }
                        count--;
                    }
                }
            });
            // 关闭线程池
            es.shutdown();
            // 阻塞操作,等待5s
            boolean finished = es.awaitTermination(5, TimeUnit.SECONDS);
            // 如果过了5s线程还没有完成, 强制关闭, interrupt Runnable 线程,  进入 InterruptedException 处理流程
            if (!finished) {
                es.shutdownNow();
            }
            System.out.println("task 3");
        }
    }
    2019-07-17 19:02:21
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
面向失败设计 立即下载
fibjs 模块重构从回调到协程--陈垒 立即下载
fibjs 模块重构从回调到协程 立即下载