0
Javaメソッドを最大X秒間実行する必要があります。 X秒後にメソッドのコードが終了しない場合は、実行を続行する必要があります。Android:メソッドを実行してタイムアウト後に終了する
(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;
}
}
私がこのコードから期待しているのは、logcatに5秒ごとに "executed!"という文字列を印刷することです。 10回。 しかし、実行は無限ループで停止します。