【问题标题】:Android: execute a method and terminate it after a timeoutAndroid:执行一个方法并在超时后终止它
【发布时间】:2016-10-18 20:33:22
【问题描述】:

我需要执行一个 Java 方法最多 X 秒。 如果方法的代码在 X 秒后没有终止,我需要继续执行。

我尝试使用以下代码(使用 ExecutorService 类)。

private void execLoop(){
    ExecutorService executor = Executors.newSingleThreadExecutor();
    int iteration;
    for(iteration=0;iteration<10;iteration++) {
        CallableTask ct = new CallableTask();
        Future<String> future = executor.submit(ct);
        try {
            future.get(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
class CallableTask implements Callable {
    @Override
    public Object call() throws Exception {
        Log.d("TIME","executed!");
        int t=0;
        boolean c = true;
        while(c){
            t+=0; // infinite loop: this method will never terminate
        }
        return null;
    }
}

我对这段代码的期望是每 5 秒向 logcat 打印一次字符串“已执行!” 10次​​。 但是,执行陷入了无限循环。

【问题讨论】:

    标签: java android timeout


    【解决方案1】:

    首先,您永远不会关闭您的执行程序。将以下行添加为 execLoop() 方法中的最后一条语句:

    executor.shutdownNow();
    

    那么,由于关闭是通过中断你的线程来完成的,你需要确保你的CallableTask 监听到中断。一种方法是使用Thread.sleep() 而不是t+=0

    while(c){
        Thread.sleep(500); // This will be interrupted when you call shutdownNow()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      相关资源
      最近更新 更多